ios 如何使用 SwiftyJSON 遍历 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28365939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:42:45  来源:igfitidea点击:

How to loop through JSON with SwiftyJSON?

iosjsonswiftswifty-json

提问by Cherif

I have a json that I could parse with SwiftyJSON :

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

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

Works perfectly.

完美运行。

But I couldn't loop through it. I tried two methods, the first one is

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

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

XCode didn't accept the for loop declaration.

XCode 不接受 for 循环声明。

The second method :

第二种方法:

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

XCode didn't accept the if statement.

XCode 不接受 if 语句。

What am I doing wrong ?

我究竟做错了什么 ?

回答by rintaro

If you want loop through json["items"]array, try:

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

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

As for the second method, .arrayValuereturns nonOptionalarray, you should use .arrayinstead:

至于第二种方法,.arrayValue返回Optional数组,你应该.array改用:

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

回答by CularBytes

I Find it a bit strange explained myself, because actually using:

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

for (key: String, subJson: JSON) in json {
   //Do something you want
}

gives syntax errors (in Swift 2.0 atleast)

给出语法错误(至少在 Swift 2.0 中)

correct was:

正确的是:

for (key, subJson) in json {
//Do something you want
}

Where indeed key is a string and subJson is a JSON object.

其中 key 确实是一个字符串,而 subJson 是一个 JSON 对象。

However I like to do it a little bit different, here is an example:

但是我喜欢做一些不同的事情,这是一个例子:

//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!)
                }
            }
        }
   }

回答by Dhruv Ramani

In the for loop, the type of keycan't be of the type "title". Since "title"is a string, go for : key:String. And then Inside the Loop you can specifically use "title"when you need it. And also the type ofsubJsonhas to be JSON.

在 for 循环中,类型key不能是类型"title"。因为"title"是一个字符串,所以去 : key:String。然后在循环内部,您可以"title"在需要时专门使用它。而且类型subJson必须是JSON.

And Since a JSON file can be considered as a 2D array, the json["items'].arrayValuewill return multiple objects. It is highly advisable to use : if let title = json["items"][2].arrayValue.

并且由于可以将 JSON 文件视为二维数组,因此json["items'].arrayValue将返回多个对象。强烈建议使用 : if let title = json["items"][2].arrayValue

Have a look at : https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html

看看:https: //developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html

回答by tangplin

Please check the 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
}

回答by 2rahulsk

you can iterate through the json by:

您可以通过以下方式遍历 json:

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

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

   print(title)

}

have a look at the documentation of SwiftyJSON. https://github.com/SwiftyJSON/SwiftyJSONgo through the Loop section of the documentation

看看 SwiftyJSON 的文档。 https://github.com/SwiftyJSON/SwiftyJSON浏览文档的循环部分