SwiftyJSON is a Swift framework built to remove the need for optional chaining in normal JSON serialization.
You can download it here: https://github.com/SwiftyJSON/SwiftyJSON
Without SwiftyJSON, your code would look like this to find the name of the first book in a JSON object:
if let jsonObject = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]],
let bookName = (jsonObject[0]["book"] as? [String: AnyObject])?["name"] as? String {
//We can now use the book name
}
In SwiftyJSON, this is hugely simplified:
let json = JSON(data: data)
if let bookName = json[0]["book"]["name"].string {
//We can now use the book name
}
It removes the need to check every field, as it will return nil if any of them are invalid.
To use SwiftyJSON, download the correct version from the Git repository - there is a branch for Swift 3. Simply drag the “SwiftyJSON.swift” into your project and import into your class:
import SwiftyJSON
You can create your JSON object using the following two initializers:
let jsonObject = JSON(data: dataObject)
or
let jsonObject = JSON(jsonObject) //This could be a string in a JSON format for example
To access your data, use subscripts:
let firstObjectInAnArray = jsonObject[0]
let nameOfFirstObject = jsonObject[0]["name"]
You can then parse your value to a certain data type, which will return an optional value:
let nameOfFirstObject = jsonObject[0]["name"].string //This will return the name as a string
let nameOfFirstObject = jsonObject[0]["name"].double //This will return null
You can also compile your paths into a swift Array:
let convolutedPath = jsonObject[0]["name"][2]["lastName"]["firstLetter"].string
Is the same as: