• This repository has been archived on 18/Jun/2019
  • Stars
    star
    1,956
  • Rank 23,701 (Top 0.5 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

[Deprecated] The easy to use Swift JSON decoder

⚠️ DEPRECATED

Unbox is deprecated in favor of Swift’s built-in Codable API and the Codextended project. All current users are highly encouraged to migrate to Codable as soon as possible. Click here for more information and a migration guide.


Unbox

Unbox | Wrap

Travis status CocoaPods Carthage Twitter: @johnsundell

Unbox is an easy to use Swift JSON decoder. Don't spend hours writing JSON decoding code - just unbox it instead!

Unbox is lightweight, non-magical and doesn't require you to subclass, make your JSON conform to a specific schema or completely change the way you write model code. It can be used on any model with ease.

Basic example

Say you have your usual-suspect User model:

struct User {
    let name: String
    let age: Int
}

That can be initialized with the following JSON:

{
    "name": "John",
    "age": 27
}

To decode this JSON into a User instance, all you have to do is make User conform to Unboxable and unbox its properties:

struct User {
    let name: String
    let age: Int
}

extension User: Unboxable {
    init(unboxer: Unboxer) throws {
        self.name = try unboxer.unbox(key: "name")
        self.age = try unboxer.unbox(key: "age")
    }
}

Unbox automatically (or, actually, Swift does) figures out what types your properties are, and decodes them accordingly. Now, we can decode a User like this:

let user: User = try unbox(dictionary: dictionary)

or even:

let user: User = try unbox(data: data)

Advanced example

The first was a pretty simple example, but Unbox can decode even the most complicated JSON structures for you, with both required and optional values, all without any extra code on your part:

struct SpaceShip {
    let type: SpaceShipType
    let weight: Double
    let engine: Engine
    let passengers: [Astronaut]
    let launchLiveStreamURL: URL?
    let lastPilot: Astronaut?
    let lastLaunchDate: Date?
}

extension SpaceShip: Unboxable {
    init(unboxer: Unboxer) throws {
        self.type = try unboxer.unbox(key: "type")
        self.weight = try unboxer.unbox(key: "weight")
        self.engine = try unboxer.unbox(key: "engine")
        self.passengers = try unboxer.unbox(key: "passengers")
        self.launchLiveStreamURL = try? unboxer.unbox(key: "liveStreamURL")
        self.lastPilot = try? unboxer.unbox(key: "lastPilot")

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "YYYY-MM-dd"
        self.lastLaunchDate = try? unboxer.unbox(key: "lastLaunchDate", formatter: dateFormatter)
    }
}

enum SpaceShipType: Int, UnboxableEnum {
    case apollo
    case sputnik
}

struct Engine {
    let manufacturer: String
    let fuelConsumption: Float
}

extension Engine: Unboxable {
    init(unboxer: Unboxer) throws {
        self.manufacturer = try unboxer.unbox(key: "manufacturer")
        self.fuelConsumption = try unboxer.unbox(key: "fuelConsumption")
    }
}

struct Astronaut {
    let name: String
}

extension Astronaut: Unboxable {
    init(unboxer: Unboxer) throws {
        self.name = try unboxer.unbox(key: "name")
    }
}

Error handling

Decoding JSON is inherently a failable operation. The JSON might be in an unexpected format, or a required value might be missing. Thankfully, Unbox takes care of handling both missing and mismatched values gracefully, and uses Swift’s do, try, catch pattern to return errors to you.

You don’t have to deal with multiple error types and perform any checking yourself, and you always have the option to manually exit an unboxing process by throwing. All errors returned by Unbox are of the type UnboxError.

Supported types

Unbox supports decoding all standard JSON types, like:

  • Bool
  • Int, Double, Float
  • String
  • Array
  • Dictionary

It also supports all possible combinations of nested arrays & dictionaries. As you can see in the Advanced example above (where an array of the unboxable Astronaut struct is being unboxed), we can unbox even a complicated data structure with one simple call to unbox().

Finally, it also supports URL through the use of a transformer, and Date by using any DateFormatter.

Transformations

Unbox also supports transformations that let you treat any value or object as if it was a raw JSON type.

It ships with a default String -> URL transformation, which lets you unbox any URL property from a string describing an URL without writing any transformation code.

The same is also true for String -> Int, Double, Float, CGFloat transformations. If you’re unboxing a number type and a string was found, that string will automatically be converted to that number type (if possible).

To enable your own types to be unboxable using a transformation, all you have to do is make your type conform to UnboxableByTransform and implement its protocol methods.

Here’s an example that makes a native Swift UniqueIdentifier type unboxable using a transformation:

struct UniqueIdentifier: UnboxableByTransform {
    typealias UnboxRawValueType = String

    let identifierString: String

    init?(identifierString: String) {
        if let UUID = NSUUID(uuidString: identifierString) {
            self.identifierString = UUID.uuidString
        } else {
            return nil
        }
    }

    static func transform(unboxedValue: String) -> UniqueIdentifier? {
        return UniqueIdentifier(identifierString: unboxedValue)
    }
}

Formatters

If you have values that need to be formatted before use, Unbox supports using formatters to automatically format an unboxed value. Any DateFormatter can out of the box be used to format dates, but you can also add formatters for your own custom types, like this:

enum Currency {
    case usd(Int)
    case sek(Int)
    case pln(Int)
}

struct CurrencyFormatter: UnboxFormatter {
    func format(unboxedValue: String) -> Currency? {
        let components = unboxedValue.components(separatedBy: ":")

        guard components.count == 2 else {
            return nil
        }

        let identifier = components[0]

        guard let value = Int(components[1]) else {
            return nil
        }

        switch identifier {
        case "usd":
            return .usd(value)
        case "sek":
            return .sek(value)
        case "pln":
            return .pln(value)
        default:
            return nil
        }
    }
}

You can now easily unbox any Currency using a given CurrencyFormatter:

struct Product: Unboxable {
    let name: String
    let price: Currency

    init(unboxer: Unboxer) throws {
        name = try unboxer.unbox(key: "name")
        price = try unboxer.unbox(key: "price", formatter: CurrencyFormatter())
    }
}

Supports JSON with both Array and Dictionary root objects

No matter if the root object of the JSON that you want to unbox is an Array or Dictionary - you can use the same Unbox() function and Unbox will return either a single model or an array of models (based on type inference).

Built-in enum support

You can also unbox enums directly, without having to handle the case if they failed to initialize. All you have to do is make any enum type you wish to unbox conform to UnboxableEnum, like this:

enum Profession: Int, UnboxableEnum {
    case developer
    case astronaut
}

Now Profession can be unboxed directly in any model

struct Passenger: Unboxable {
    let profession: Profession

    init(unboxer: Unboxer) throws {
        self.profession = try unboxer.unbox(key: "profession")
    }
}

Contextual objects

Sometimes you need to use data other than what's contained in a dictionary during the decoding process. For this, Unbox has support for strongly typed contextual objects that can be made available in the unboxing initializer.

To use contextual objects, make your type conform to UnboxableWithContext, which can then be unboxed using unbox(dictionary:context) where context is of the type of your choice.

Key path support

You can also use key paths (for both dictionary keys and array indexes) to unbox values from nested JSON structures. Let's expand our User model:

{
    "name": "John",
    "age": 27,
    "activities": {
        "running": {
            "distance": 300
        }
    },
    "devices": [
        "Macbook Pro",
        "iPhone",
        "iPad"
    ]
}
struct User {
    let name: String
    let age: Int
    let runningDistance: Int
    let primaryDeviceName: String
}

extension User: Unboxable {
    init(unboxer: Unboxer) throws {
        self.name = try unboxer.unbox(key: "name")
        self.age = try unboxer.unbox(key: "age")
        self.runningDistance = try unboxer.unbox(keyPath: "activities.running.distance")
        self.primaryDeviceName = try unboxer.unbox(keyPath: "devices.0")
    }
}

You can also use key paths to directly unbox nested JSON structures. This is useful when you only need to extract a specific object (or objects) out of the JSON body.

{
    "company": {
        "name": "Spotify",
    },
    "jobOpenings": [
        {
            "title": "Swift Developer",
            "salary": 120000
        },
        {
            "title": "UI Designer",
            "salary": 100000
        },
    ]
}
struct JobOpening {
    let title: String
    let salary: Int
}

extension JobOpening: Unboxable {
    init(unboxer: Unboxer) throws {
        self.title = try unboxer.unbox(key: "title")
        self.salary = try unboxer.unbox(key: "salary")
    }
}

struct Company {
    let name: String
}

extension Company: Unboxable {
    init(unboxer: Unboxer) throws {
        self.name = try unboxer.unbox(key: "name")
    }
}
let company: Company = try unbox(dictionary: json, atKey: "company")
let jobOpenings: [JobOpening] = try unbox(dictionary: json, atKey: "jobOpenings")
let featuredOpening: JobOpening = try unbox(dictionary: json, atKeyPath: "jobOpenings.0")

Custom unboxing

Sometimes you need more fine grained control over the decoding process, and even though Unbox was designed for simplicity, it also features a powerful custom unboxing API that enables you to take control of how an object gets unboxed. This comes very much in handy when using Unbox together with Core Data, when using dependency injection, or when aggregating data from multiple sources. Here's an example:

let dependency = DependencyManager.loadDependency()

let model: Model = try Unboxer.performCustomUnboxing(dictionary: dictionary, closure: { unboxer in
    var model = Model(dependency: dependency)
    model.name = try? unboxer.unbox(key: "name")
    model.count = try? unboxer.unbox(key: "count")

    return model
})

Installation

CocoaPods:

Add the line pod "Unbox" to your Podfile

Carthage:

Add the line github "johnsundell/unbox" to your Cartfile

Manual:

Clone the repo and drag the file Unbox.swift into your Xcode project.

Swift Package Manager:

Add the line .Package(url: "https://github.com/johnsundell/unbox.git", from: "3.0.0") to your Package.swift

Platform support

Unbox supports all current Apple platforms with the following minimum versions:

  • iOS 8
  • OS X 10.11
  • watchOS 2
  • tvOS 9

Debugging tips

In case your unboxing code isn’t working like you expect it to, here are some tips on how to debug it:

Compile time error: Ambiguous reference to member 'unbox'

Swift cannot find the appropriate overload of the unbox method to call. Make sure you have conformed to any required protocol (such as Unboxable, UnboxableEnum, etc). Note that you can only conform to one Unbox protocol for each type (that is, a type cannot be both an UnboxableEnum and UnboxableByTransform). Also remember that you can only reference concrete types (not Protocol types) in order for Swift to be able to select what overload to use.

unbox() throws

Use the do, try, catch pattern to catch and handle the error:

do {
    let model: Model = try unbox(data: data)
} catch {
    print("An error occurred: \(error)")
}

If you need any help in resolving any problems that you might encounter while using Unbox, feel free to open an Issue.

Community Extensions

Hope you enjoy unboxing your JSON!

For more updates on Unbox, and my other open source projects, follow me on Twitter: @johnsundell

Also make sure to check out Wrap that let’s you easily encode JSON.

More Repositories

1

Publish

A static site generator for Swift developers
Swift
4,840
star
2

SwiftTips

A collection of Swift tips & tricks that I've shared on Twitter
3,971
star
3

Files

A nicer way to handle files & folders in Swift
Swift
2,456
star
4

Ink

A fast and flexible Markdown parser written in Swift.
Swift
2,377
star
5

Plot

A DSL for writing type-safe HTML, XML and RSS in Swift.
Swift
1,979
star
6

Marathon

[DEPRECATED] Marathon makes it easy to write, run and manage your Swift scripts πŸƒ
Swift
1,863
star
7

ImagineEngine

A project to create a blazingly fast Swift game engine that is a joy to use πŸš€
Swift
1,825
star
8

SwiftPlate

Easily generate cross platform Swift framework projects from the command line
Swift
1,766
star
9

Splash

A fast, lightweight and flexible Swift syntax highlighter for blogs, tools and fun!
Swift
1,758
star
10

TestDrive

Quickly try out any Swift pod or framework in a playground
Swift
1,597
star
11

Codextended

Extensions giving Swift's Codable API type inference super powers πŸ¦Έβ€β™‚οΈπŸ¦Ήβ€β™€οΈ
Swift
1,495
star
12

ShellOut

Easily run shell commands from a Swift script or command line tool
Swift
836
star
13

Wrap

[DEPRECATED] The easy to use Swift JSON encoder
Swift
732
star
14

CollectionConcurrencyKit

Async and concurrent versions of Swift’s forEach, map, flatMap, and compactMap APIs.
Swift
730
star
15

Sweep

Fast and powerful Swift string scanning made simple
Swift
531
star
16

Playground

Instantly create Swift playgrounds from the command line
Swift
439
star
17

Require

Require optional values to be non-nil, or crash gracefully
Swift
414
star
18

XcodeTheme

My Xcode theme - Sundell's Colors
Swift
408
star
19

AsyncCompatibilityKit

iOS 13-compatible backports of commonly used async/await-based system APIs that are only available from iOS 15 by default.
Swift
378
star
20

Shapeshift

Quickly convert a folder containing Swift files into an iPad-compatible Playground
Swift
338
star
21

Identity

πŸ†” Type-safe identifiers in Swift
Swift
298
star
22

SwiftBySundell

Code samples from the Swift by Sundell website & podcast
Swift
289
star
23

SwiftScripting

A list of Swift scripting tools, frameworks & examples
235
star
24

SuperSpriteKit

Extensions to Apple's SpriteKit game engine
Objective-C
224
star
25

Flow

Operation Oriented Programming in Swift
Swift
217
star
26

Xgen

A Swift package for generating Xcode workspaces & playgrounds
Swift
189
star
27

IndieSupportWeeks

A two-week effort to help support indie developers shipping apps on Apple's platforms who have been financially impacted by the COVID-19 pandemic.
182
star
28

CGOperators

Easily manipulate CGPoints, CGSizes and CGVectors using math operators
Swift
148
star
29

Animate

Declarative UIView animations without nested closures
Swift
129
star
30

SplashPublishPlugin

A Splash plugin for the Publish static site generator
Swift
92
star
31

Assert

A collection of convenient assertions for Swift testing
Swift
69
star
32

UITestingExample

Example code from my blog post about UI testing
Swift
67
star
33

Marathon-Examples

A collection of example Swift scripts that can easily be run using Marathon
Swift
55
star
34

Releases

A Swift package for resolving released versions from a Git repository
Swift
51
star
35

BlockSnippets

Xcode snippets that are very handy when working with blocks in various contexts
51
star
36

PlotPlayground

A Swift playground that comes pre-loaded with Plot, that can be used to explore the new component API.
Swift
49
star
37

SwiftKit

A collection of Swift utilities that I share across my Swift-based projects
Swift
38
star
38

UnitTestingWorkshop

Project used during my workshop "Getting started with unit testing in Swift"
Swift
36
star
39

JSUpdateLookup

A lightweight, easy to use Objective-C class to check if your iOS app has an update available
Objective-C
28
star
40

SwiftAveiro

Skeleton project for my Swift Aveiro workshop "Everyone is an API designer"
Swift
15
star
41

CloudKitChat

A demo chat application powered by CloudKit
Objective-C
14
star
42

swiftbysundell-beta-feedback

Submit your feedback on the Swift by Sundell 2.0 beta
9
star
43

JSGeometry

A set of utility functions that enables easy one-line manipulation of CoreGraphics geometry structs like CGPoint, CGSize & CGRect.
Objective-C
6
star
44

JSAutoCopy

An Objective-C category that enables automatic copying of any object
Objective-C
4
star
45

UnboxDemoPlayground

A Swift Playground that comes setup with Unbox & Wrap, used in my CocoaHeads Stockholm presentation
Swift
3
star
46

JSAutoEncodedObject

Automatically encode or decode any Objective-C object
Objective-C
3
star
47

JSLocalization

An Objective-C class that enables dynamic localization of an iOS app.
Objective-C
3
star
48

MarathonTestScriptWithDependencies

A test script with dependencies - used for Marathon's tests
Swift
2
star
49

JSObservableObject

Easily add protocol-based observation to any Objective-C class
Objective-C
2
star
50

MarathonTestScript

A Swift script that's used in Marathon's tests
Swift
1
star
51

MarathonTestPackage

A Swift package that's used in Marathon's tests
Swift
1
star