Swift 3 中解析 JSON

Xcode 8 和 Swift 3id 现在作为 Any 引入而不是 AnyObject

这表示 JSONSerialization.jsonObject(with: data) 返回 Any。所以需要把 json data 转换为特定类型,比如[String:Any]。json 接下来的字段也需要这么做。

var jsonString = "{" +
    "\"Language\": {" +
    "\"Field\":[" +
    "{" +
    "\"Number\":\"976\"," +
    "\"Name\":\"Test1\"" +
    "}," +
    "{" +
    "\"Number\":\"977\"," +
    "\"Name\":\"Test2\"" +
    "}" +
    "]" +
    "}" +
"}"

var data = jsonString.data(using: .utf8)!
if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] {
    let language = parsedData["Language"] as! [String:Any]
    print(language)
    let field = language["Field"] as! [[String:Any]]
    let name = field[0]["Name"]!
    print(name) // ==> Test1
}

实际中你应该想要 json 深处特定的字段。就假设是 Field 数组的第一个元素 Name 字段。可以用一串展开来安全的访问字段,就像这样:

var data = jsonString.data(using: .utf8)!
if let json = try? JSONSerialization.jsonObject(with: data) as? [String:Any],
    let language = json?["Language"] as? [String:Any],
    let field = language["Field"] as? [[String:Any]],
    let name = field[0]["Name"] as? String, field.count > 0 {
    print(name) // ==> Test1
} else {
    print("bad json - do some recovery")
}

参考:苹果Swift 博客 Working with JSON in Swift

你可能感兴趣的:(Swift 3 中解析 JSON)