如何使用SwiftyJSON循环遍历JSON数据?

36

我有一个可以使用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语句。

我做错了什么?

5个回答

79

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

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

至于第二种方法,.arrayValue 返回一个非 Optional 的数组,你应该使用 .array 代替:

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

当我尝试循环遍历我的[String: JSON]字典时,我会收到错误提示:'[String : JSON]?'没有名为'Generator'的成员。 - mattgabor
因为它是可选的 - nikans
@rintaro 我使用了您的方法,它能用,但我不确定它是否高效。如果您有多个要捕获的 items(例如标题、作者、评论),您会简单地重复 if let <<newItem>> = item["<<newItem>>"].string {} 来捕获每个吗? - Craig.Pearce
@Craig.Pearce 基本上是的。但如果你在意“效率”,我认为你不应该使用SwiftyJSON。请参见:SwiftyJSON性能问题 - rintaro
@rintaro - 非常有趣。对于我最初的应用程序,SwiftyJSON 应该可以胜任,但我会收藏这个 SO 对话以备将来参考。谢谢。 - Craig.Pearce

11

我觉得有点奇怪解释自己,因为实际上使用的是:

for (key: String, subJson: JSON) in json {
   //Do something you want
}
在Swift2.0中,会出现语法错误(至少如此)。正确的方式是:
for (key, subJson) in json {
//Do something you want
}

确切地说,key是一个字符串,subJson是一个JSON对象。

然而,我喜欢做得有点不同,这里有一个例子:

//jsonResult from API request,JSON result from Alamofire
   if let jsonArray = jsonResult?.array
    {
        //it is an array, each array contains a dictionary
        for item in jsonArray
        {
            if let jsonDict = item.dictionary //jsonDict : [String : JSON]?
            {
                //loop through all objects in this jsonDictionary
                let postId = jsonDict!["postId"]!.intValue
                let text = jsonDict!["text"]!.stringValue
                //...etc. ...create post object..etc.
                if(post != nil)
                {
                    posts.append(post!)
                }
            }
        }
   }

正确的语法是 for (key, subJson):(String, JSON) in json。 - Emptyless

8

如果我帮到了您,请在左侧勾选那个绿色标签。谢谢! - Dhruv Ramani

1
请检查README
//If json is .Dictionary
for (key: String, subJson: JSON) in json {
   //Do something you want
}

//If json is .Array
//The `index` is 0..<json.count's string value
for (index: String, subJson: JSON) in json {
    //Do something you want
}

1
他在问题中表示他检查了文档。我认为这并没有什么帮助。抱歉。 - John Shelley
这对我帮助很大。谢谢。 - derickito

0

您可以通过以下方式迭代JSON:

for (_,subJson):(String, JSON) in json {

   var title = subJson["items"]["2"]["title"].stringValue

   print(title)

}

请查看SwiftyJSON的文档。 https://github.com/SwiftyJSON/SwiftyJSON 仔细阅读文档中的Loop部分。


1
虽然这可能回答了作者的问题,但它缺少一些解释性的词语和/或文档链接。裸代码片段没有周围的一些短语是不太有用的。您也可以在如何撰写好的答案中找到很多帮助。请编辑您的答案 - 来自审核 - Nick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接