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

JSONEncodable

mdmathias edited this page Sep 15, 2016 · 2 revisions

Encoding to JSON

JSONDecodable is a protocol that helps to decode JSON into a model type. But what if you want to go from a model instance to JSON? JSONEncodable is what you are looking for.

Recall our canonical Person type:

public struct Person: CustomStringConvertible {
    public let name: String
    public var age: Int
    public let spouse: Bool
    
    public var description: String {
        return "Name: \(name), age: \(age), married: \(spouse)"
    }
}

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")
    }
}

Like JSONDecodable, JSONEncodable is a protocol. A type can conforms to JSONEncodable so that an instance can be encoded into JSON.

extension Person: JSONEncodable {
    public func toJSON() -> JSON {
        return .dictionary(["name": .string(name), "age": .int(age), "spouse": .bool(spouse)])
    }
}

The Person type conforms to JSONEncodable in an extension. All that is required for a type to conform is to provide an implementation of toJSON(), which returns an instance of JSON. Thus, the Person type's implementation creates a JSON.Dictionary containing an instance's property values.

Serializing JSON to Data

One benefit of having your models JSONEncodable is that it is easy to create instances of Data from instances of your model. This is nice if you have to send your models back up to some web service.

Imagine that you have an array of Person instances:

let people = [ Person(name: "Matt", age: 32, spouse: true), Person(name: "Drew", age: 33, spouse: true) ]

Because Freddy extends Array to conform to JSONEncodable, you can encode this array to JSON like so:

let peopleJSON = people.toJSON()

Getting Data from peopleJSON is trivial.

do {
    let peopleData = try peopleJSON.serialize()
    // Call web service with `peopleData`
} catch {
    // Do something with `error`
}
Clone this wiki locally