如何使用Swift将以下数据提取到tableview中?

时间:2016-06-25 09:52:21

标签: swift alamofire

首先让我们看看json数据。

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

我使用过Alamofire并通过以下代码获得回复:

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)")

                }
            }

但在获得响应数据后,我无法获得任何价值。在这里,我想获取所有数据,如name,id和subcategory - 如何实现这个?

1 个答案:

答案 0 :(得分:1)

那里有一个以上的问题。 第一个响应的类型为response.result.value,它不是您要查找的已解析对象,而是应该像使用日志一样使用response.result.value。 第二,即使你试图将Array<Dictionary<String,String>>强制转换为subcategory,它也不会通过,因为在你的json数据中你有内部数组Dictionary<String, String>无法转换为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"] } } }

此代码适用于您:

OpenCV4Android

以下是操场上的结果:enter image description here

干杯。