在 Swift 中遍历嵌入式 JSON 数组?



我正在尝试遍历嵌入式 JSON 数组并提取所有值以放入本地数组中。 这是 JSON 的样子:

"welcome": {
"data": {
"tncUrl": ""
},
"items": [
{
"newUser": [
{
"stepConcept": false
},
{
"stepSafety": true
},
{
"stepFacilitator": true
},
{
"stepTransparency": true
}
],
"switcher": [
{
"stepConcept": true
},
{
"stepSafety": true
},
{
"stepFacilitator": true
},
{
"stepTransparency": true
}
]
}
]
}

我能够达到一个点,我可以看到我正在检索"newUser"的值,问题是循环访问这些值并将它们添加到数组中。这样做时我收到EXC_BAD_INSTRUCTION错误。这是我用来获取这些值的代码:

func prepareArrayOfViews(userType: User)
{
if (welcomeJSON != nil)
{
let items : NSArray? = welcomeJSON!.value(forKey: "items") as? NSArray
if (items == nil)
{
listOfViews = ["stepConcept", "stepSafety", "stepFacilitator", "stepTransparency"]
maxPages = listOfViews.count
return
}
if (items != nil) {
if let newUser = (items?.value(forKey: "newUser") as? NSArray){
//Below is where the error "EXC_BAD_INSTRUCTION"
for key in (newUser as! NSDictionary).allKeys
{
if (((newUser as! NSDictionary).value(forKey: key as! String) as? Bool)!)
{
listOfViews.append(key as! String)
}
}
}
if (listOfViews.count == 0)
{
listOfViews = ["stepConcept", "stepSafety", "stepFacilitator", "stepTransparency"]
}
maxPages = listOfViews.count
}
}
}

我已经更改了您的代码以使用本机 Swift 结构。由于当您的可选解包不起作用时,您没有处理错误或执行任何操作,因此我还将解包更改为保护语句。

除了 Swift 编码实践的严重问题之外,您的问题是您试图将一系列字典作为简单的字典进行迭代。

func prepareArrayOfViews(userType: User){
guard let welcomeJSON = welcomeJSON else {return}
guard let items = welcomeJSON["items"] as? [[String:Any]] else {
listOfViews = ["stepConcept", "stepSafety", "stepFacilitator", "stepTransparency"]
maxPages = listOfViews.count
return
}
for item in items {
if let newUser = item["newUser"] as? [[String:Any]] {
for embeddedDict in newUser {
for (key, value) in embeddedDict { 
if let val = value as? Bool, val == true {
listOfViews.append(key)
}
}
}
} else if let switcher = item["switcher"] as? [[String:Any]]{
for embeddedDict in switcher {
for (key, value) in embeddedDict { 
if let val = value as? Bool, val == true {
//do whatever you need to with the value
}
}
}
}
}
if (listOfViews.count == 0){
listOfViews = ["stepConcept", "stepSafety", "stepFacilitator", "stepTransparency"]
}   
maxPages = listOfViews.count
}

因为

//here newUser is an NSArray
if let newUser = (items?.value(forKey: "newUser") as? NSArray){
//here newUser forced to NSDictionary 
for key in (newUser as! NSDictionary).allKeys

尝试将此部分更改为

if let newUsers = (items?.value(forKey: "newUser") as? NSArray){
for newUser in newUsers
{
for key in (newUser as! NSDictionary).allKeys
{
if (((newUser as! NSDictionary).value(forKey: key as! String) as? Bool)!)
{
listOfViews.append(key as! String)
}
}
}
}

最新更新