Integrating our apps with HTTP APIs often involves a fair amount of "busy work". Writing models to match API responses, manually iterating each field in a JSON object, and typing each in as a Swift property can be a bummer. Today we'll check out a great new tool from Josh Smith called json2swift that can help us here. It can generate Swift model code from a JSON object. Let's give it a try.
After we've installed json2swift, we can run it like this:
json2swift Spaceship.json
This will create a new file called Spaceship.swift
in the same directory as our .json
.
This means if our Spaceship.json
file looked like this:
{
"name": "Tantive IV",
"topSpeed": 950
}
The resulting json2swift-generated Swift model would look like this:
struct RootType: CreatableFromJSON {
let name: String
let topSpeed: Int
}
Neat!
json2swift has generated an immutable Swift struct from our JSON file. Pro Tip: We can also run this on a directory full of JSON files, and it will process all of them.
json2swift will even try to determine which properties should be optional, and which are required. It will then generate the appropriate init
code.
We're even provided some special handling for things like Date parsing. If we put a special String like this in our original JSON:
{
"name" : "Tantive IV".
"buildDate" : "DATE_FORMAT=yyyy-MM-dd"
}
This will give us a:
let buildDate: Date
property, as well as generate the appropriate Date format/parsing code needed to make it work. Neat!
We've only scratched the surface, json2swift has great support for intelligenty inferring types for things like numbers, and even URLs. Learn more about json2swift at git.io/json2swift.