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 Jan 20, 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 value: JSON) throws {
        name = try value.string("name")
        age = try value.int("age")
        spouse = try value.bool("spouse")
    }
}

Person conforms to JSONDecodable in an extension. Since the various calls to string(_:), int(_:), and bool(_:) 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