gpt4 book ai didi

ios - Swift2 - 在嵌套 JSON 中使用 Alamofire 3

转载 作者:行者123 更新时间:2023-11-30 12:51:13 26 4
gpt4 key购买 nike

我有以下 JSON:

{
"_embedded": {
"modifier_groups": [
{
"_embedded": {
"options": [
{
"id": "8kT9KTX7",
"name": "Perfect",
"open": false,
"pos_id": "8kT9KTX7",
"price_per_unit": 0
},
{
"id": "zRcEkcj8",
"name": "Overcooked",
"open": false,
"pos_id": "zRcEkcj8",
"price_per_unit": 0
}
]
},
"id": "eMiy4iR4",
"maximum": 1,
"minimum": 1,
"name": "Temperature",
"required": false
},
{
"_embedded": {
"options": [
{
"id": "E5cpac84",
"name": "Tomato",
"open": false,
"pos_id": "E5cpac84",
"price_per_unit": 0
},
{
"id": "GkiREiyL",
"name": "Cheese",
"open": false,
"pos_id": "GkiREiyL",
"price_per_unit": 100
}
]
},
"id": "kMT85Tay",
"maximum": null,
"minimum": 1,
"name": "Toppings",
"required": false
}
]
},
"count": 2,
"limit": 20
}

因此有修饰符组名称(例如“温度”和“配料”)和组选项(例如“温度”组的“完美”和“煮过头”)。

我想做的是构建一个[String],例如:

["Temperature - Perfect", "Temperature - Overcooked", "Toppings - Tomato", "Toppings - Cheese"]

最快的方法是什么?

目前,我首先使用 valueForKeyPath 将组提取到 [String] 中:

Alamofire.request(.GET, url, headers: headers, encoding: .JSON)
.responseJSON { response in
switch response.result {
case .Success(let JSON):
let jsonData = JSON as? NSDictionary
let groupNames = jsonData?.valueForKeyPath("_embedded.modifier_groups.name")

但是我如何从那里更深入地研究组选项,以便将它们附加到 [String] 中?

更新

我尝试了这个,但它没有返回任何内容:

var mods = [String]()

let modGroups = jsonData?.valueForKeyPath("_embedded.modifier_groups")

if let modGroups = modGroups {
for modGroup in modGroups as! [AnyObject] {
let groupOptions = modGroups.valueForKeyPath("_embedded.options")
if let groupOptions = groupOptions {
for groupOption in groupOptions as! [AnyObject] {
mods.append("\(modGroup) - \(groupOption)")
}
}
}
}

最佳答案

明白了:

var mods = [String]()

let modGroups = jsonData?.valueForKeyPath("_embedded.modifier_groups") as? [NSDictionary]

if let modGroups = modGroups {
for modGroup in modGroups {
let groupOptions = modGroup.valueForKeyPath("_embedded.options") as? [NSDictionary]
if let groupOptions = groupOptions {
for groupOption in groupOptions {
mods.append("\(modGroup.valueForKey("name")!) - \(groupOption.valueForKey("name")!)")
}
}
}
}

关于ios - Swift2 - 在嵌套 JSON 中使用 Alamofire 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40940916/

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