Swift,循环遍历JSON返回Null

时间:2016-02-02 22:40:27

标签: json swift swifty-json

我正在尝试循环遍历json文件中的band列表(使用Swifty-Json),由于某种原因,当我开始循环遍历名称时,它返回null。

的Json

JSON的小片段

[  
{  
  "Band":{  
     "ID":"1",
     "Name":"The Kooks"
  }
},
{  
  "Band":{  
     "ID":"2",
     "Name":"The Killers"
  }
}
]

Swift Code

 for (_, value) in json {
    for (_,band) in value["Band"] {
       for (_,bandname) in band["Name"] {
           print("Band name: \(bandname)")
       }
     }
 }

上面的代码返回:

  

乐队名称:null

     

乐队名称:null

     

乐队名称:null

     

乐队名称:null

当我尝试这个时:

for (_, value) in json {
   for (_,brand) in value["Band"] {
      print(band)
   }
}

我得到了这个结果:

  

The Kooks

     

1

     

杀手

     

2

谁能告诉我这是什么问题?

1 个答案:

答案 0 :(得分:1)

由于与键相关联的值"名称"是一个简单的字符串,你想使用:

for (_, value) in json {
    for (_,band) in value["Band"] {
       if let bandname = band["Name"].string {
           print("Band name: \(bandname)")
       } else {
           print("No name specified")
       }
    }
}