如何使用SwiftyJSON循环JSON?

Che*_*rif 34 json ios swift swifty-json

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

if let title = json["items"][2]["title"].string {
     println("title : \(title)")
}
Run Code Online (Sandbox Code Playgroud)

完美的工作.

但我无法绕过它.我试过两种方法,第一种是

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

XCode不接受for循环声明.

第二种方法:

// TUTO :
if let appArray = json["feed"]["entry"].arrayValue {
     ...
}
// WHAT I DID :
if let tab = json["items"].arrayValue {
     ...
}
Run Code Online (Sandbox Code Playgroud)

XCode不接受if语句.

我究竟做错了什么 ?

rin*_*aro 75

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

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

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

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


Cul*_*tes 10

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

for (key: String, subJson: JSON) in json {
   //Do something you want
}
Run Code Online (Sandbox Code Playgroud)

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

正确的是:

for (key, subJson) in json {
//Do something you want
}
Run Code Online (Sandbox Code Playgroud)

确实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!)
                }
            }
        }
   }
Run Code Online (Sandbox Code Playgroud)


Dhr*_*ani 8

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

由于JSON文件可以被视为2D数组,因此json["items'].arrayValue将返回多个对象.最好使用:if let title = json["items"][2].arrayValue.

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