PRADIP KUMAR PRADIP KUMAR - 5 months ago 12
Swift Question

How to define array of arrays

I am trying to fetch the Json data from Api which is in the following format

[
{
"id": "244",
"name": "PIZZAS",
"image": "",
"coupon": "1",
"icon": "",
"order": "1",
"aname": "",
"options": "2",
"subcategory": [
{
"id": "515",
"name": "MARGARITA",
"description": "Cheese and Tomato",
"image": "",
"icon": "",
"coupon": "1",
"order": "1",
"aname": "",
"options": "2",
"item": [
{
"id": "1749",
"name": "9 Inch Thin & Crispy Margarita",
"description": "",
"price": "3.40",
"coupon": "1",
"image": "",
"options": "2",
"order": "1",
"addon": "495",
"aname": "",
"icon": ""
},
{
"id": "1750",
"name": "12 Inch Thin & Crispy Margarita",
"description": "",
"price": "5.20",
"coupon": "1",
"image": "",
"options": "2",
"order": "2",
"addon": "496",
"aname": "",
"icon": ""
}
]
}


How can i fetch the "subcategory name" as well as " items name". Please help me out.I have written some codes and tried to fetch but not working.

var json: NSArray!
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as? NSArray

} catch {
print(error)
}

self.AllData = json.valueForKey("subcategory") as! Array<String>
print(self.AllData)
print(self.AllData.count)


But its not fetching any value
Other way also I have tried but still no data fetching . only the data is coming in json1.

do {
let json1 = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
// print(json1)

if let subcategory = json1["subcategory"] as? [[String: AnyObject]] {
for subname in subcategory {
if let name = subname["name"] as? String {
print(name)
}
if let items = subname["item"] as? [[String: AnyObject]] {
for item in items {
if let itemName = item["name"] as? String {
print(itemName)
}
}
}
}
}
} catch {
print(error)
}

Answer

This may just be a problem when cutting and pasting into the question, but it looks like your JSON data isn't formatted correctly (the []s and {}s don't match up). As the previous commentor said, you're dealing with an array of dictionaries not an array of strings. Try something like this:

do {
    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())

    if let subs = json["subcategory"] as? [[String: AnyObject]] {
        for sub in subs {
            if let name = sub["name"] as? String {
                print(name)
            }
            if let items = sub["item"] as? [[String: AnyObject]] {
                for item in items {
                    if let itemName = item["name"] as? String {
                        print(itemName)
                    }
                }
            }
        }
    }
} catch {
    print(error)
}