gpt4 book ai didi

ios - 在 swift 中访问 json 数据的正确方法

转载 作者:行者123 更新时间:2023-11-30 12:03:25 29 4
gpt4 key购买 nike

我正在尝试访问 json 文件中的数据,但不完全确定如何访问。我正在尝试访问此 json 中的“animation_file”:

 "items": [{
"newUser": {
"steps": [
{
"id": 0,
"step_title": "stepConcept",
"visible": false,
"animation_file": "Welcome_Step_01_V01"
},
{
"id": 1,
"step_title": "stepSafety",
"visible": true,
"animation_file": "Welcome_Step_02_V01"
},
{
"id": 2,
"step_title": "stepFacilitator",
"visible": true,
"animation_file": "Welcome_Step_03_V01"
},
{
"id": 3,
"step_title": "stepTransparency",
"visible": true,
"animation_file": "Welcome_Step_04_V01"
}
]
},

这是我到目前为止所拥有的:

 guard let items = welcomeJSON["items"] as? [[String:Any]] else {return}

for item in items {
if (isNewUser) {
if let newUser = item["newUser"] as? [String:Any] {
if let steps = newUser["steps"] as? [[String:Any]] {
for embeddedDict in steps {
for (key, value) in embeddedDict {
if let val = value as? Bool, val == true {
print(key)
newUserViews.append(key)
}
}
}
} else {
listOfViews = newUserViews
listOfViews = [STEP_CONCEPT, STEP_SAFETY, STEP_FACILITATOR, STEP_TRANSPARENCY]
maxPages = listOfViews.count
return
}
}
}

这看起来正确吗?我觉得我可能错过了一步。

最佳答案

如果我理解正确的话,只有当visible的值为true并且您想将其放入newUserViews数组中时,您才会尝试获取“animation_file”的值。下面的代码应该可以帮助您:

guard let items = welcomeJSON["items"] as? [[String:Any]] else {return}

for item in items {
if (isNewUser) {
if let newUser = item["newUser"] as? [String:Any] {
if let steps = newUser["steps"] as? [[String:Any]] {
for embeddedDict in steps {
if let visible = newUser["visible"] as? Bool, visible == true, let animationFile = newUser["animation_file"] as? String {
newUserViews.append(animationFile)
}
}
} else {
listOfViews = newUserViews
listOfViews = [STEP_CONCEPT, STEP_SAFETY, STEP_FACILITATOR, STEP_TRANSPARENCY]
maxPages = listOfViews.count
return
}
}
}
}

在我看来,您的其余代码似乎不正确,但上面的代码应该可以解决您当前的问题。

关于ios - 在 swift 中访问 json 数据的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46936132/

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