-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.

Zapko
  • 2,461
  • 25
  • 30
e.k
  • 1,333
  • 1
  • 17
  • 36
  • https://stackoverflow.com/questions/41734982/parsing-nested-array-of-dictionaries-using-object-mapper/41735194#41735194 – Umair Afzal Jul 06 '17 at 04:44
  • Possible duplicate of [Correctly Parsing JSON in Swift 3](https://stackoverflow.com/questions/39423367/correctly-parsing-json-in-swift-3) – vadian Jul 07 '17 at 04:00

1 Answers1

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{

}
Fangming
  • 24,551
  • 6
  • 100
  • 90