如何获取名称值,多层JSON值

时间:2014-08-20 07:15:05

标签: json swift

我怎样才能获得名称的价值。谢谢! webservice返回这个json:

{
    "msg":"ok",
    "content":[{"id":"123","status":"10","date":"2014-08-20","name":"abc"}]
}

如何获取名称值,多层JSON值。 我可以获得msg值,但名称值...什么方法

1 个答案:

答案 0 :(得分:0)

JSON很难看。这就是你如何获得"name"

import Foundation


let jsonTestString = "{\"msg\":\"ok\",\"content\":[{\"id\":\"123\",\"status\":\"10\",\"date\":\"2014-08-20\",\"name\":\"abc\"}]}"
let jsonTestData = jsonTestString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

if let data = jsonTestData {
    let jsonDictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as [String : AnyObject]
    let content = jsonDictionary["content"] as AnyObject? as? [[String : String]]
    let name = content?.first?["name"]
    println(name ?? "There is no name.") // prints abc.
}

注意这一行:

let content = jsonDictionary["content"] as AnyObject? as? [[String : String]]

我们应该能够有条件地直接向[[String : String]]投降:

let content = jsonDictionary["content"] as? [[String : String]]

它是known bug