{"id":15130646,"url":"https://github.com/johnsundell/unbox","last_synced_at":"2025-10-20T13:34:25.045Z","repository":{"id":33252287,"uuid":"36896680","full_name":"JohnSundell/Unbox","owner":"JohnSundell","description":"[Deprecated] The easy to use Swift JSON decoder","archived":true,"fork":false,"pushed_at":"2019-04-08T13:57:08.000Z","size":920,"stargazers_count":1940,"open_issues_count":35,"forks_count":161,"subscribers_count":37,"default_branch":"master","last_synced_at":"2024-12-29T04:22:11.683Z","etag":null,"topics":["decoding","json","json-parsing","swift","swift-json-decoder","unbox"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/JohnSundell.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-06-04T21:35:32.000Z","updated_at":"2024-10-29T16:04:41.000Z","dependencies_parsed_at":"2022-08-17T21:40:37.192Z","dependency_job_id":null,"html_url":"https://github.com/JohnSundell/Unbox","commit_stats":null,"previous_names":[],"tags_count":28,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnSundell%2FUnbox","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnSundell%2FUnbox/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnSundell%2FUnbox/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnSundell%2FUnbox/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JohnSundell","download_url":"https://codeload.github.com/JohnSundell/Unbox/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234563123,"owners_count":18853056,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["decoding","json","json-parsing","swift","swift-json-decoder","unbox"],"created_at":"2024-09-26T03:03:13.770Z","updated_at":"2025-09-28T20:31:48.507Z","avatar_url":"https://github.com/JohnSundell.png","language":"Swift","readme":"⚠️ **DEPRECATED**\n\nUnbox is deprecated in favor of Swift’s built-in `Codable` API and [the Codextended project](https://github.com/JohnSundell/Codextended). All current users are highly encouraged to migrate to `Codable` as soon as possible. [Click here for more information and a migration guide](CodableMigrationGuide.md).\n\n---\n\n\u003cp align=\"center\"\u003e\n    \u003cimg src=\"logo.png\" width=\"300\" max-width=\"50%\" alt=\"Unbox\" /\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003cb\u003eUnbox\u003c/b\u003e\n    |\n    \u003ca href=\"https://github.com/johnsundell/wrap\"\u003eWrap\u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://travis-ci.org/JohnSundell/Unbox/branches\"\u003e\n        \u003cimg src=\"https://img.shields.io/travis/JohnSundell/Unbox/master.svg\" alt=\"Travis status\" /\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://cocoapods.org/pods/Unbox\"\u003e\n        \u003cimg src=\"https://img.shields.io/cocoapods/v/Unbox.svg\" alt=\"CocoaPods\" /\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/Carthage/Carthage\"\u003e\n        \u003cimg src=\"https://img.shields.io/badge/carthage-compatible-4BC51D.svg?style=flat\" alt=\"Carthage\" /\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://twitter.com/johnsundell\"\u003e\n        \u003cimg src=\"https://img.shields.io/badge/contact-@johnsundell-blue.svg?style=flat\" alt=\"Twitter: @johnsundell\" /\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\nUnbox is an easy to use Swift JSON decoder. Don't spend hours writing JSON decoding code - just unbox it instead!\n\nUnbox 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.\n\n### Basic example\n\nSay you have your usual-suspect `User` model:\n\n```swift\nstruct User {\n    let name: String\n    let age: Int\n}\n```\n\nThat can be initialized with the following JSON:\n\n```json\n{\n    \"name\": \"John\",\n    \"age\": 27\n}\n```\n\nTo decode this JSON into a `User` instance, all you have to do is make `User` conform to `Unboxable` and unbox its properties:\n\n```swift\nstruct User {\n    let name: String\n    let age: Int\n}\n\nextension User: Unboxable {\n    init(unboxer: Unboxer) throws {\n        self.name = try unboxer.unbox(key: \"name\")\n        self.age = try unboxer.unbox(key: \"age\")\n    }\n}\n```\n\nUnbox automatically (or, actually, Swift does) figures out what types your properties are, and decodes them accordingly. Now, we can decode a `User` like this:\n\n```swift\nlet user: User = try unbox(dictionary: dictionary)\n```\nor even:\n```swift\nlet user: User = try unbox(data: data)\n```\n\n### Advanced example\n\nThe 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:\n\n```swift\nstruct SpaceShip {\n    let type: SpaceShipType\n    let weight: Double\n    let engine: Engine\n    let passengers: [Astronaut]\n    let launchLiveStreamURL: URL?\n    let lastPilot: Astronaut?\n    let lastLaunchDate: Date?\n}\n\nextension SpaceShip: Unboxable {\n    init(unboxer: Unboxer) throws {\n        self.type = try unboxer.unbox(key: \"type\")\n        self.weight = try unboxer.unbox(key: \"weight\")\n        self.engine = try unboxer.unbox(key: \"engine\")\n        self.passengers = try unboxer.unbox(key: \"passengers\")\n        self.launchLiveStreamURL = try? unboxer.unbox(key: \"liveStreamURL\")\n        self.lastPilot = try? unboxer.unbox(key: \"lastPilot\")\n\n        let dateFormatter = DateFormatter()\n        dateFormatter.dateFormat = \"YYYY-MM-dd\"\n        self.lastLaunchDate = try? unboxer.unbox(key: \"lastLaunchDate\", formatter: dateFormatter)\n    }\n}\n\nenum SpaceShipType: Int, UnboxableEnum {\n    case apollo\n    case sputnik\n}\n\nstruct Engine {\n    let manufacturer: String\n    let fuelConsumption: Float\n}\n\nextension Engine: Unboxable {\n    init(unboxer: Unboxer) throws {\n        self.manufacturer = try unboxer.unbox(key: \"manufacturer\")\n        self.fuelConsumption = try unboxer.unbox(key: \"fuelConsumption\")\n    }\n}\n\nstruct Astronaut {\n    let name: String\n}\n\nextension Astronaut: Unboxable {\n    init(unboxer: Unboxer) throws {\n        self.name = try unboxer.unbox(key: \"name\")\n    }\n}\n```\n\n### Error handling\n\nDecoding 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.\n\nYou 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`.\n\n### Supported types\n\nUnbox supports decoding all standard JSON types, like:\n\n- `Bool`\n- `Int`, `Double`, `Float`\n- `String`\n- `Array`\n- `Dictionary`\n\nIt also supports all possible combinations of nested arrays \u0026 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()`.\n\nFinally, it also supports `URL` through the use of a transformer, and `Date` by using any `DateFormatter`.\n\n### Transformations\n\nUnbox also supports transformations that let you treat any value or object as if it was a raw JSON type.\n\nIt ships with a default `String` -\u003e `URL` transformation, which lets you unbox any `URL` property from a string describing an URL without writing any transformation code.\n\nThe same is also true for `String` -\u003e `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).\n\nTo 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.\n\nHere’s an example that makes a native Swift `UniqueIdentifier` type unboxable using a transformation:\n\n```swift\nstruct UniqueIdentifier: UnboxableByTransform {\n    typealias UnboxRawValueType = String\n\n    let identifierString: String\n\n    init?(identifierString: String) {\n        if let UUID = NSUUID(uuidString: identifierString) {\n            self.identifierString = UUID.uuidString\n        } else {\n            return nil\n        }\n    }\n\n    static func transform(unboxedValue: String) -\u003e UniqueIdentifier? {\n        return UniqueIdentifier(identifierString: unboxedValue)\n    }\n}\n```\n\n### Formatters\n\nIf 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:\n\n```swift\nenum Currency {\n    case usd(Int)\n    case sek(Int)\n    case pln(Int)\n}\n\nstruct CurrencyFormatter: UnboxFormatter {\n    func format(unboxedValue: String) -\u003e Currency? {\n        let components = unboxedValue.components(separatedBy: \":\")\n\n        guard components.count == 2 else {\n            return nil\n        }\n\n        let identifier = components[0]\n\n        guard let value = Int(components[1]) else {\n            return nil\n        }\n\n        switch identifier {\n        case \"usd\":\n            return .usd(value)\n        case \"sek\":\n            return .sek(value)\n        case \"pln\":\n            return .pln(value)\n        default:\n            return nil\n        }\n    }\n}\n```\n\nYou can now easily unbox any `Currency` using a given `CurrencyFormatter`:\n\n```swift\nstruct Product: Unboxable {\n    let name: String\n    let price: Currency\n\n    init(unboxer: Unboxer) throws {\n        name = try unboxer.unbox(key: \"name\")\n        price = try unboxer.unbox(key: \"price\", formatter: CurrencyFormatter())\n    }\n}\n```\n\n### Supports JSON with both Array and Dictionary root objects\n\nNo 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).\n\n### Built-in enum support\n\nYou 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:\n\n```swift\nenum Profession: Int, UnboxableEnum {\n    case developer\n    case astronaut\n}\n```\n\nNow `Profession` can be unboxed directly in any model\n\n```swift\nstruct Passenger: Unboxable {\n    let profession: Profession\n\n    init(unboxer: Unboxer) throws {\n        self.profession = try unboxer.unbox(key: \"profession\")\n    }\n}\n```\n\n### Contextual objects\n\nSometimes 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.\n\nTo 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.\n\n### Key path support\n\nYou 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:\n\n```json\n{\n    \"name\": \"John\",\n    \"age\": 27,\n    \"activities\": {\n        \"running\": {\n            \"distance\": 300\n        }\n    },\n    \"devices\": [\n        \"Macbook Pro\",\n        \"iPhone\",\n        \"iPad\"\n    ]\n}\n```\n\n```swift\nstruct User {\n    let name: String\n    let age: Int\n    let runningDistance: Int\n    let primaryDeviceName: String\n}\n\nextension User: Unboxable {\n    init(unboxer: Unboxer) throws {\n        self.name = try unboxer.unbox(key: \"name\")\n        self.age = try unboxer.unbox(key: \"age\")\n        self.runningDistance = try unboxer.unbox(keyPath: \"activities.running.distance\")\n        self.primaryDeviceName = try unboxer.unbox(keyPath: \"devices.0\")\n    }\n}\n```\n\nYou 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.\n\n```json\n{\n    \"company\": {\n        \"name\": \"Spotify\",\n    },\n    \"jobOpenings\": [\n        {\n            \"title\": \"Swift Developer\",\n            \"salary\": 120000\n        },\n        {\n            \"title\": \"UI Designer\",\n            \"salary\": 100000\n        },\n    ]\n}\n```\n\n```swift\nstruct JobOpening {\n    let title: String\n    let salary: Int\n}\n\nextension JobOpening: Unboxable {\n    init(unboxer: Unboxer) throws {\n        self.title = try unboxer.unbox(key: \"title\")\n        self.salary = try unboxer.unbox(key: \"salary\")\n    }\n}\n\nstruct Company {\n    let name: String\n}\n\nextension Company: Unboxable {\n    init(unboxer: Unboxer) throws {\n        self.name = try unboxer.unbox(key: \"name\")\n    }\n}\n```\n\n```swift\nlet company: Company = try unbox(dictionary: json, atKey: \"company\")\nlet jobOpenings: [JobOpening] = try unbox(dictionary: json, atKey: \"jobOpenings\")\nlet featuredOpening: JobOpening = try unbox(dictionary: json, atKeyPath: \"jobOpenings.0\")\n```\n\n### Custom unboxing\n\nSometimes 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:\n\n```swift\nlet dependency = DependencyManager.loadDependency()\n\nlet model: Model = try Unboxer.performCustomUnboxing(dictionary: dictionary, closure: { unboxer in\n    var model = Model(dependency: dependency)\n    model.name = try? unboxer.unbox(key: \"name\")\n    model.count = try? unboxer.unbox(key: \"count\")\n\n    return model\n})\n```\n\n### Installation\n\n**CocoaPods:**\n\nAdd the line `pod \"Unbox\"` to your `Podfile`\n\n**Carthage:**\n\nAdd the line `github \"johnsundell/unbox\"` to your `Cartfile`\n\n**Manual:**\n\nClone the repo and drag the file `Unbox.swift` into your Xcode project.\n\n**Swift Package Manager:**\n\nAdd the line `.Package(url: \"https://github.com/johnsundell/unbox.git\", from: \"3.0.0\")` to your `Package.swift`\n\n### Platform support\n\nUnbox supports all current Apple platforms with the following minimum versions:\n\n- iOS 8\n- OS X 10.11\n- watchOS 2\n- tvOS 9\n\n### Debugging tips\n\nIn case your unboxing code isn’t working like you expect it to, here are some tips on how to debug it:\n\n**Compile time error: `Ambiguous reference to member 'unbox'`**\n\nSwift 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.\n\n**`unbox()` throws**\n\nUse the `do, try, catch` pattern to catch and handle the error:\n\n```swift\ndo {\n    let model: Model = try unbox(data: data)\n} catch {\n    print(\"An error occurred: \\(error)\")\n}\n```\n\nIf you need any help in resolving any problems that you might encounter while using Unbox, feel free to open an Issue.\n\n### Community Extensions\n\n- [UnboxedAlamofire](https://github.com/serejahh/UnboxedAlamofire) - the easiest way to use Unbox with Alamofire\n\n### Hope you enjoy unboxing your JSON!\n\nFor more updates on Unbox, and my other open source projects, follow me on Twitter: [@johnsundell](http://www.twitter.com/johnsundell)\n\nAlso make sure to check out [Wrap](http://github.com/johnsundell/wrap) that let’s you easily **encode** JSON.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnsundell%2Funbox","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjohnsundell%2Funbox","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnsundell%2Funbox/lists"}