Search code examples
swift3json-serialization

How to parse json response swift3?


My response looks like this:

[
    {
        "Part" : {
            "id" : "418502",
            "uuid" : "21ec7cdb-cd2d-4b12-8a90-775762eb0f26"
        },
        "Category" : {
            "category_name" : "Regulators",
            "category_code" : "RG"
        }
    },
    {
        "Part" : {
             "id" : "418502",
             "uuid" : "21ec7cdb-cd2d-4b12-8a90-775762eb0f26"
        },
        "Category" : {
             "category_name" : "Regulators",
             "category_code" : "RG"
        }
    }
]

So I need to parse the above response to get Part array and Category array. After searching in google I found:

let resultJson = try JSONSerialization.jsonObject(with: data, options: []) as? [String : AnyObject]
print(resultJson!)

But it throws fatal error: unexpectedly found nil while unwrapping an Optional value.

I'm new to swift I don't know how to convert it. I have completed this in Android so I can surely say I get above response from server. I write a common function for calling web service, it works for other services so I think there is no problem in that.

How can I parse my response so I can get Part array and Category array? Thank you.


Solution

  • Your JSON structure has a top level array, so you cannot parse is as a dictionary. Try to do this

    let resultJson = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
    dump(resultJson!)
    

    Sample code will be something like this. Don't forget to handle unwrap stuff

    let str = "[{\"Part\":{\"id\":\"418502\",\"uuid\":\"21ec7cdb-cd2d-4b12-8a90-775762eb0f26\"},\"Category\":{\"category_name\":\"Regulators\",\"category_code\":\"RG\"}},{\"Part\":{\"id\":\"418502\",\"uuid\":\"21ec7cdb-cd2d-4b12-8a90-775762eb0f26\"},\"Category\":{\"category_name\":\"Regulators\",\"category_code\":\"RG\"}}]"
    
    let data = str.data(using: .utf8)
    
    do{
        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [Any]
        let dicInFirstElement = json?[0] as? [String: Any]
        let part = dicInFirstElement?["Part"]
        dump(part)
        //Pass this json into the following function
    }catch let error{
    
    }