Simple JSON parsing into custom objects

suggest change

Third-party libraries are optional. A protocol is enough for a simple parser. Imagine a Todo:

struct Todo {
    let comment: String
}

When the JSON arrives, turn the Data (NSData in Swift 2) into an object with JSONSerialization, as the other JSON examples do.

After that, using a simple protocol JSONDecodable

typealias JSONDictionary = [String:AnyObject]
protocol JSONDecodable {
    associatedtype Element
    static func from(json: JSONDictionary) -> Element?
}

Make Todo conform to JSONDecodable:

extension Todo: JSONDecodable {
    static func from(json: JSONDictionary) -> Todo? {
        guard let comment = json["comment"] as? String else { return nil }
        return Todo(comment: comment)
    }
}

You can try it with this json code:

{
    "todos": [
        {
            "comment" : "The todo comment"
        }
    ]
}

After the API response is serialized, dictionary is that value. Check that it is a JSONDictionary:

guard let jsonDictionary = dictionary as? JSONDictionary else { return }

This JSON stores the todos in an array, so check that next:

guard let todosDictionary = jsonDictionary["todos"] as? [JSONDictionary] else { return }

Convert each dictionary into a Todo. flatMap drops the nil values. Swift 4.1 and later name that operation compactMap.

let todos: [Todo] = todosDictionary.flatMap { Todo.from(json: $0) }

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents