1

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?
}

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.