Skip to content
This repository has been archived by the owner on Sep 19, 2018. It is now read-only.

JSONDecodable

mdmathias edited this page Sep 15, 2016 · 6 revisions

Freddy provides a protocol to help create instances of model types from JSON.

public protocol JSONDecodable {
    init(json: JSON) throws
}

JSONDecodable requires conforming types to implement an initializer: init(json:). This initializer takes an instance of JSON, and potentially throws if there is an error. A conforming type implements this method to use a JSON to create an instance of itself.

Let's take a look at how the Person type conforms to JSONDecodable.

extension Person: JSONDecodable {
    public init(json: JSON) throws {
        name = try json.getString(at: "name")
        age = try json.getInt(at: "age")
        spouse = try json.getBool(at: "spouse")
    }
}

Person conforms to JSONDecodable in an extension. Since the various calls to getString(at:), getInt(at:), and getBool(at:) can generate an error, we have to call each with a try. This also means that the initializer must be marked with throws. If no error occurs, then the properties are given their values and an instance of Person is created. If an error does occur, then an informative error is thrown telling the caller what went wrong.

Clone this wiki locally