SwiftyJSON
suggest changeSwiftyJSON 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:
// Swift 2. Swift 3 and later: JSONSerialization.jsonObject(with: data, options: .allowFragments)
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 = try 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 = try JSON(data: dataObject)
or
let jsonObject = JSON(jsonObject)
// This wraps a value. A String becomes a JSON string; it is not parsed. Use JSON(data:) or JSON(parseJSON:) to parse text.
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 // nil when the value is not a number
The same path can be one subscript:
let convolutedPath = jsonObject[0]["name"][2]["lastName"]["firstLetter"].string
Is the same as:
let convolutedPath = jsonObject[0, "name", 2, "lastName", "firstLetter"].string
SwiftyJSON also has functionality to print its own errors:
if let name = json[1337].string {
//You can use the value - it is valid
} else {
print(json[1337].error) // Optional(SwiftyJSONError.indexOutOfBounds) - the value is not usable
}
If you need to write to your JSON object, you can use subscripts again:
var originalJSON:JSON = ["name": "Jack", "age": 18]
originalJSON["age"] = 25 //This changes the age to 25
originalJSON["surname"] = "Smith" //This creates a new field called "surname" and adds the value to it
Should you need the original String for the JSON, for example if you need to write it to a file, you can get the raw value out:
if let string = json.rawString() { //This is a String object
//Write the string to a file if you like
}
if let data = try? json.rawData() { //This is a Data object
//Send the data to your server if you like
}