ios - 如何使用 SwiftyJSON 遍历 JSON?

我有一个可以用 SwiftyJSON 解析的 json:

if let title = json["items"][2]["title"].string {
     println("title : \(title)")
}

完美运行。

但我无法遍历它。我尝试了两种方法,第一种是

// TUTO :
//If json is .Dictionary
for (key: String, subJson: JSON) in json {
    ...
}
// WHAT I DID :
for (key: "title", subJson: json["items"]) in json {
    ...
}

XCode 不接受 for 循环声明。

第二种方法:

// TUTO :
if let appArray = json["feed"]["entry"].arrayValue {
     ...
}
// WHAT I DID :
if let tab = json["items"].arrayValue {
     ...
}

XCode 不接受 if 语句。

我做错了什么?

最佳答案

如果你想循环遍历 json["items"] 数组,试试:

for (key, subJson) in json["items"] {
    if let title = subJson["title"].string {
        println(title)
    }
}

至于第二种方法,.arrayValue返回non 可选数组,你应该使用.array代替:

if let items = json["items"].array {
    for item in items {
        if let title = item["title"].string {
            println(title)
        }
    }
}

https://stackoverflow.com/questions/28365939/

相关文章:

json - 如何在 Mac 上通过命令行安装 JQ?

json - 如何强制将请求正文解析为纯文本而不是 Express 中的 json?

c# - 将对象序列化为 JSON 时循环引用检测到异常

java - 用于生成和使用 JSON 的 Controller 的 Spring RequestM

java - Jersey 异常 : SEVERE: A message body reader f

ios - waitUntilAllTask​​sAreFinished 错误 Swift

javascript - Javascript对象和JSON对象有什么区别

json - 在单行上从 jq 获取输出

java - Jackson JSON 字段映射大小写?

java - 使用 GSON 解析 JSON 文件