nickjf89 nickjf89 - 29 days ago 13
Swift Question

Parsing JSON response in Swift 3

I've got an API endpoint that returns JSON in the following format:

[
{
"id": "1",
"name": "John"
},
{
"id": "2",
"name": "Jane"
},
{
"id": "3",
"name": "Nick"
}
]


I am trying to parse this in Swift 3, but I can only find examples to parse JSON formatted like so:

{
"blogs": [
{
"needspassword": true,
"id": 73,
"url": "http://remote.bloxus.com/",
"name": "Bloxus test"
},
{
"needspassword": false,
"id": 74,
"url": "http://flickrtest1.userland.com/",
"name": "Manila Test"
}
],
"stat": "ok"
}


, which has an extra level above what mine does.

So, where examples I've seen are simply parsing their data like
jsonResponse["blogs"]
, I can't do that as my format is different.

How can I parse the format I've got, or how can I return a format that is easier to parse?

Any suggestions appreciated, thanks!

Answer

This will parse it when placed in the network call.

        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as! [[String : AnyObject]]
            let firstPerson = json[0]
            print(firstPerson)
            let id = firstPerson["id"] as! String
            print(id)
            let name = firstPerson["name"] as! String
            print(name)
        } catch {
            //handle error
        }

Also, I tend to be against advising third party libraries, but SwiftyJSON is an exception I make. If you want to try it, add this to your pod file:

pod SwiftyJSON', '3.0.0'

Documentation: https://github.com/SwiftyJSON/SwiftyJSON