JSON parsing using Swift at Nakko

JSON parsing using Swift at Nakko

Having to build iOS apps that use data coming from a server you usually find yourself in the need to exchange a lot of JSON data back and forth with the server providing such data. Now you all know that that can be a pain and if not done right you can have tons of issues with your app crashing and a lot of the times you just feel left alone in the dark trying to figure out what's happening. Not to mention the time that it takes to parse all that data into your own model objects. Sure, it was pretty easy with Objective-C, but since Apple launch Swift it become even more of pain.

Let me explain what I mean by that. Let's say you have the following JSON string coming in from the server:

{
    "name": "Mickey",
    "id": {
        "series": "TC",
        "number": 123456
    }
}

And your app has these 2 simple classes you want to parse the data into:

class User {
    var name: String!
    var id: UserID!
}

class UserID {
    var series: String!
    var number: Int = 0
}

Now the standard Swift way to parse this is horrible, at least that's what we thought. You would have to use NSJSONSerialization to get the JSON string converted into a dictionary and then you would have to manually go trough all the keys your interested in and make sure they're the right type and assign the correct value to the correct property of your class. Now, believe me... That takes a while! And to be honest I'm not even going to demonstrate that now, 'cause that's not the purpose of this article.

I want to show you how we handle JSON here at Nakko. And to make things shorter, well, here's how the 2 classes would look like in our source code:

class User: JSONParsable {
    var name: String!
    var id: UserID!

    required init(JSON: NKJSON) {
        name <> JSON["name"]
        id <*> JSON["id"]
    }
}

class UserID: JSONParsable {
    var series: String!
    var number: Int = 0

    required init(JSON: NKJSON) {
        series <> JSON["series"]
        number <> JSON["number"]
    }
}

That's it! To put things in motion add one more line of code where you fetch your data (that is NSData for Swift) and you're done:

if let user: User = NKJSON.parse(data) {
    // Your user object is there! Believe me, use it!
}

Simple, right?

I know, I know... You're asking yourself what's with all those crazy operators, what do they mean, and all that. Well, why not go and take a look on GitHub at the project? NKJSON is open-source and it's available to you starting today.

Grab the source, play with it, use it, leave some feedback, maybe add some improvements (and contribute those back if you please), but most importantly, enjoy it!

 

Update: Added NKJSON.rootKey class variable used for accessing the whole underlaying JSON dictionary. See Example on GitHub6for details

De Logo banner

New site