gpt4 book ai didi

swift - 如何使用 Swift 将以下数据获取到 tableview 中?

转载 作者:行者123 更新时间:2023-11-30 10:01:57 26 4
gpt4 key购买 nike

首先让我们看看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)")

}
}

但是在获取响应数据后我无法获得任何值。这里我想获取所有数据,如名称、ID 和子类别 - 如何实现?

最佳答案

您遇到的问题不止一个。第一个响应的类型为 Response<Anyobject, NSError> ,这不是您正在寻找的解析对象,而是您应该使用 response.result.value正如您对日志所做的那样。其次,即使您尝试转换 response.result.valueArray<Dictionary<String,String>>它不会通过,因为在你的 json 数据中你有一个内部数组 subcategory不能转换为 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"]
}

}
}

这是 Playground 上的结果:enter image description here

干杯。

关于swift - 如何使用 Swift 将以下数据获取到 tableview 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38027160/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com