simbolo simbolo - 4 months ago 13
iOS Question

Parse JSON string to object using Swift

Does anyone have a working example on how to parse a JSON array to a collection of objects? All the various examples found on the web/SO seem to break between versions of XCode/Swift.

This is to work in the latest XCode (XCode 6). All the different options I've tried have thrown up errors that just go round in circles.

Sample JSON:

[
{ id: 1, name: "test" },
{ id: 2, name: "test" }
]


My object:

class MyItem {
var id: Int32?
var name: String?
}

Answer

I change your definition of MyItem and add extension for printing.

class MyItem {
    var id: Int?
    var name: String?

    init(id: Int?, name: String?){
        self.id = id
        self.name = name
    }
}

extension MyItem: Printable {
    var description: String {
        return "\(self.id!): \(self.name!)"
    }
}

And convert source string to a collection:

var source = "[{ \"id\": 1, \"name\": \"test\" },{ \"id\": 2, \"name\": \"test\" }]"
var results: [MyItem] = []

var err:NSError?
var obj:AnyObject? = NSJSONSerialization.JSONObjectWithData(source.dataUsingEncoding(NSUTF8StringEncoding)!, options:nil, error:&err)
if let items = obj as? NSArray {
    for itemDict in items as [NSDictionary] {
        var item: MyItem = MyItem(id: itemDict.valueForKey("id")?.integerValue, name: itemDict.objectForKey("name") as? String)
        results.append(item)
    }
}
println(results)

Some nil cases aren't considered. Just give you a example. You can use this popular lib: https://github.com/SwiftyJSON/SwiftyJSON and trace code in detail if interested.