[英]How to loop through JSON with SwiftyJSON?
我有一個可以用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
返回非 Optional
數組,您應該改用.array
:
if let items = json["items"].array {
for item in items {
if let title = item["title"].string {
println(title)
}
}
}
我發現我自己解釋有點奇怪,因為實際上使用了:
for (key: String, subJson: JSON) in json {
//Do something you want
}
給出語法錯誤(在Swift 2.0中至少)
正確的是:
for (key, subJson) in json {
//Do something you want
}
實際上,鍵是字符串,而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
的類型不能為"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
請檢查自述文件
//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
}
您可以通過以下方式遍歷json:
for (_,subJson):(String, JSON) in json {
var title = subJson["items"]["2"]["title"].stringValue
print(title)
}
看看SwiftyJSON的文檔。 https://github.com/SwiftyJSON/SwiftyJSON瀏覽文檔的Loop部分
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.