我试图访问json文件中的数据但不完全确定如何访问。我试图访问" animation_file"在这个json:
"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
}
}
}
这看起来是否正确?我觉得我可能错过了一步。
答案 0 :(得分:0)
如果我理解正确,只有当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
}
}
}
}
我的其余代码似乎并不正确,但上面的代码应解决您当前的问题。