我是swift的新手,并尝试调用结果的JSON数据的Web服务。它的结构如下:
{
temp : [
{
key1:value1
key2:value2
key3:value3
}
{
key1:value1
key2:value2
key3:value3
}
{
key1:value1
key2:value2
key3:value3
}
]
}
我能够得到结果JSON。但是我怎么能遍历这个词典。我想显示所有字典中的value2。
任何帮助将不胜感激
提前致谢
答案 0 :(得分:0)
像这样:
let dictArray:[[String:String]] = [["k1":"v1" ,"k2":"v2", "k3":"v3"], ["k1":"v1" ,"k2":"v2", "k3":"v3"]]
for dict in dictArray {
for (key, val) in dict {
if val == "v2" {
println(key)
}
}
}
我想您更想获得密钥的价值,但您的问题有点误导。
答案 1 :(得分:0)
想象一下这是我的本地json文件:
Json文件:
{
"temp" : [
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
]
}
解析JSON并打印“key2”
值的代码var error: NSError?
// get json data from local json file
let jsonFilePath = NSBundle.mainBundle().pathForResource("MyFile", ofType: "json")!
let jsonData = NSData(contentsOfFile: jsonFilePath)!
let jsonObjects: AnyObject! = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error)
let items: NSArray! = jsonObjects["temp"] as? NSArray
for index in 0...items.count - 1 {
let item = items[index] as NSDictionary
println(item["key2"]!);
}
一些有用的链接:
祝你好运