Simple JSON parsing into custom objects

suggest change

Even if third-party libraries are good, a simple way to parse the JSON is provided by protocols You can imagine you have got an object Todo as

struct Todo {
    let comment: String
}

Whenever you receive the JSON, you can handle the plain NSData as shown in the other example using NSJSONSerialization object.

After that, using a simple protocol JSONDecodable

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

And making your Todo struct conforming to JSONDecodable does the trick

extension Todo: JSONDecodable {
    static func from(json 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"
        }
    ]
}

When you got it from the API, you can serialize it as the previous examples shown in an AnyObject instance. After that, you can check if the instance is a JSONDictionary instance

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

The other thing to check, specific for this case because you have an array of Todo in the JSON, is the todos dictionary

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

Now that you got the array of dictionaries, you can convert each of them in a Todo object by using flatMap (it will automatically delete the nil values from the array)

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