- Notifications
You must be signed in to change notification settings - Fork161
[Deprecated] The easy to use Swift JSON decoder
License
JohnSundell/Unbox
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Unbox is deprecated in favor of Swift’s built-inCodable
API andthe Codextended project. All current users are highly encouraged to migrate toCodable
as soon as possible.Click here for more information and a migration guide.
Unbox |Wrap
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.
Say you have your usual-suspectUser
model:
structUser{letname:Stringletage:Int}
That can be initialized with the following JSON:
{"name":"John","age":27}
To decode this JSON into aUser
instance, all you have to do is makeUser
conform toUnboxable
and unbox its properties:
structUser{letname:Stringletage:Int}extensionUser: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 aUser
like this:
letuser:User=tryunbox(dictionary: dictionary)
or even:
letuser:User=tryunbox(data: data)
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:
structSpaceShip{lettype:SpaceShipTypeletweight:Doubleletengine:Engineletpassengers:[Astronaut]letlaunchLiveStreamURL:URL?letlastPilot:Astronaut?letlastLaunchDate:Date?}extensionSpaceShip: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")letdateFormatter=DateFormatter() dateFormatter.dateFormat="YYYY-MM-dd"self.lastLaunchDate=try? unboxer.unbox(key:"lastLaunchDate", formatter: dateFormatter)}}enumSpaceShipType:Int,UnboxableEnum{case apollocase sputnik}structEngine{letmanufacturer:StringletfuelConsumption:Float}extensionEngine:Unboxable{init(unboxer:Unboxer)throws{self.manufacturer=try unboxer.unbox(key:"manufacturer")self.fuelConsumption=try unboxer.unbox(key:"fuelConsumption")}}structAstronaut{letname:String}extensionAstronaut:Unboxable{init(unboxer:Unboxer)throws{self.name=try unboxer.unbox(key:"name")}}
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’sdo, 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 bythrowing
. All errors returned by Unbox are of the typeUnboxError
.
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 theAdvanced example above (where an array of the unboxableAstronaut
struct is being unboxed), we can unbox even a complicated data structure with one simple call tounbox()
.
Finally, it also supportsURL
through the use of a transformer, andDate
by using anyDateFormatter
.
Unbox also supports transformations that let you treat any value or object as if it was a raw JSON type.
It ships with a defaultString
->URL
transformation, which lets you unbox anyURL
property from a string describing an URL without writing any transformation code.
The same is also true forString
->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 toUnboxableByTransform
and implement its protocol methods.
Here’s an example that makes a native SwiftUniqueIdentifier
type unboxable using a transformation:
structUniqueIdentifier:UnboxableByTransform{typealiasUnboxRawValueType=StringletidentifierString:Stringinit?(identifierString:String){iflet UUID=NSUUID(uuidString: identifierString){self.identifierString=UUID.uuidString}else{returnnil}}staticfunc transform(unboxedValue:String)->UniqueIdentifier?{returnUniqueIdentifier(identifierString: unboxedValue)}}
If you have values that need to be formatted before use, Unbox supports using formatters to automatically format an unboxed value. AnyDateFormatter
can out of the box be used to format dates, but you can also add formatters for your own custom types, like this:
enumCurrency{case usd(Int)case sek(Int)case pln(Int)}structCurrencyFormatter:UnboxFormatter{func format(unboxedValue:String)->Currency?{letcomponents= unboxedValue.components(separatedBy:":")guard components.count==2else{returnnil}letidentifier=components[0]guardlet value=Int(components[1])else{returnnil}switch identifier{case"usd":return.usd(value)case"sek":return.sek(value)case"pln":return.pln(value)default:returnnil}}}
You can now easily unbox anyCurrency
using a givenCurrencyFormatter
:
structProduct:Unboxable{letname:Stringletprice:Currencyinit(unboxer:Unboxer)throws{ name=try unboxer.unbox(key:"name") price=try unboxer.unbox(key:"price", formatter:CurrencyFormatter())}}
No matter if the root object of the JSON that you want to unbox is anArray
orDictionary
- you can use the sameUnbox()
function and Unbox will return either a single model or an array of models (based on type inference).
You can also unboxenums
directly, without having to handle the case if they failed to initialize. All you have to do is make anyenum
type you wish to unbox conform toUnboxableEnum
, like this:
enumProfession:Int,UnboxableEnum{case developercase astronaut}
NowProfession
can be unboxed directly in any model
structPassenger:Unboxable{letprofession:Professioninit(unboxer:Unboxer)throws{self.profession=try unboxer.unbox(key:"profession")}}
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 toUnboxableWithContext
, which can then be unboxed usingunbox(dictionary:context)
wherecontext
is of the type of your choice.
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" ]}
structUser{letname:Stringletage:IntletrunningDistance:IntletprimaryDeviceName:String}extensionUser: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 }, ]}
structJobOpening{lettitle:Stringletsalary:Int}extensionJobOpening:Unboxable{init(unboxer:Unboxer)throws{self.title=try unboxer.unbox(key:"title")self.salary=try unboxer.unbox(key:"salary")}}structCompany{letname:String}extensionCompany:Unboxable{init(unboxer:Unboxer)throws{self.name=try unboxer.unbox(key:"name")}}
letcompany:Company=tryunbox(dictionary: json, atKey:"company")letjobOpenings:[JobOpening]=tryunbox(dictionary: json, atKey:"jobOpenings")letfeaturedOpening:JobOpening=tryunbox(dictionary: json, atKeyPath:"jobOpenings.0")
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:
letdependency=DependencyManager.loadDependency()letmodel:Model=tryUnboxer.performCustomUnboxing(dictionary: dictionary, closure:{ unboxerinvarmodel=Model(dependency: dependency) model.name=try? unboxer.unbox(key:"name") model.count=try? unboxer.unbox(key:"count")return model})
CocoaPods:
Add the linepod "Unbox"
to yourPodfile
Carthage:
Add the linegithub "johnsundell/unbox"
to yourCartfile
Manual:
Clone the repo and drag the fileUnbox.swift
into your Xcode project.
Swift Package Manager:
Add the line.Package(url: "https://github.com/johnsundell/unbox.git", from: "3.0.0")
to yourPackage.swift
Unbox supports all current Apple platforms with the following minimum versions:
- iOS 8
- OS X 10.11
- watchOS 2
- tvOS 9
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 theunbox
method to call. Make sure you have conformed to any required protocol (such asUnboxable
,UnboxableEnum
, etc). Note that you can only conform to one Unbox protocol for each type (that is, a type cannot be both anUnboxableEnum
andUnboxableByTransform
). Also remember that you can only reference concrete types (notProtocol
types) in order for Swift to be able to select what overload to use.
unbox()
throws
Use thedo, try, catch
pattern to catch and handle the error:
do{letmodel:Model=tryunbox(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.
- UnboxedAlamofire - the easiest way to use Unbox with Alamofire
For more updates on Unbox, and my other open source projects, follow me on Twitter:@johnsundell
Also make sure to check outWrap that let’s you easilyencode JSON.
About
[Deprecated] The easy to use Swift JSON decoder