PRADIP KUMAR PRADIP KUMAR - 5 months ago 19
Swift Question

How to fetch the following data into the tableview using Swift?

First lets see the json data.

[
{
"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": ""
}]
}]
}]


I have used Alamofire and getting response through this code below:

Alamofire.request(.GET, myUrl, parameters:nil , encoding: .JSON)
.validate()
.responseString { response in
print("Response String: \(response.result.value)")
}
.responseJSON { response in
print("Response JSON: \(response.result.value)")


if let jsonResult = response as? Array<Dictionary<String,String>> {
let Name = jsonResult[0]["name"]
let ID = jsonResult[0]["id"]
let Order = jsonResult[0]["order"]

print("JSON: Name: \(Name)")
print("JSON: ID: \(ID)")
print("JSON: Order: \(Order)")

}
}


But after getting response data I am not able to get any value. Here I want to fetch all data like name,id and subcategory - how to implement this?

MAB MAB
Answer

You have more than one problem there. First response is of type Response<Anyobject, NSError>, it's not the parsed object you're looking for, instead you should use response.result.value as you did for the log. Second even if you tried to cast response.result.value to Array<Dictionary<String,String>> it will not pass because in your json data you have ann inner array subcategory which cannot be casted to Dictionary<String, String>

This code should work for you:

Alamofire.request(.GET, myUrl, parameters:nil , encoding: .JSON)
    .validate()
    .responseString { response in
        print("Response String: \(response.result.value)")
    }
    .responseJSON { response in
        print("Response JSON: \(response.result.value)")


        let array = response.result.value as! Array<NSDictionary>
        for item in array
        {
            let Name = item["name"]
            let ID = item["id"]
            let Order = item["order"]
            let Subcategories = item["subcategory"] as! Array<NSDictionary>
            for subCategory in Subcategories
            {
                let subId = subCategory["id"]
            }

        }
}

And here is the results in the playground: enter image description here

Cheers.

Comments