如何循环使用swift JSON?

时间:2022-09-23 00:00:20

I have a json that I could parse with SwiftyJSON :

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

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 ?

我做错了什么?

4 个解决方案

#1


65  

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, .arrayValue returns non Optional array, you should use .array instead:

对于第二种方法,.arrayValue返回非可选数组,您应该使用.array代替:

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

#2


8  

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)

给出语法错误(至少在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.

键是字符串,而subject是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!)
                }
            }
        }
   }

#3


5  

In the for loop, the type of key can'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 ofsubJson has to be JSON.

在for循环中,键的类型不能是“title”类型。因为“title”是一个字符串,所以输入:key: string。然后在循环中,当你需要的时候,你可以特别地使用“title”。而且主子的类型必须是JSON。

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

由于JSON文件可以看作是一个2D数组,所以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

#4


2  

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
}

#1


65  

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, .arrayValue returns non Optional array, you should use .array instead:

对于第二种方法,.arrayValue返回非可选数组,您应该使用.array代替:

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

#2


8  

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)

给出语法错误(至少在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.

键是字符串,而subject是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!)
                }
            }
        }
   }

#3


5  

In the for loop, the type of key can'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 ofsubJson has to be JSON.

在for循环中,键的类型不能是“title”类型。因为“title”是一个字符串,所以输入:key: string。然后在循环中,当你需要的时候,你可以特别地使用“title”。而且主子的类型必须是JSON。

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

由于JSON文件可以看作是一个2D数组,所以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

#4


2  

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
}