-3

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.

2

1 Answer 1

2

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{

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

4 Comments

@e.k Updated my answer. Your JSON is not correctly formatted. Correct it and let me know so that I can give you code to parse your JSON
My response in very big I just put a small part from it
@e.k Updated my answer
Yeah thank you very much. It helped now I can able to get arrays.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.