JSON Parsing in Swift 3

前端 未结 8 853
暖寄归人
暖寄归人 2020-12-01 11:05

Has anyone been able to find a way to parse through JSON files in Swift 3? I have been able to get the data to return but I am unsuccessful when it comes to breaking the dat

8条回答
  •  不知归路
    2020-12-01 11:33

    In Xcode 8 and Swift 3 id now imports as Any rather than AnyObject

    This means that JSONSerialization.jsonObject(with: data) returns Any. So you have to cast the json data to a specific type like [String:Any]. Same applies to the next fields down the 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
    }
    

    In practice you would probably want some specific field buried in the json. Lets assume it's the Name field of the first element of Field array. You can use a chain of unwraps like this to safely access the field:

    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")
    }
    

    Also you may want to check Apple's Swift Blog Working with JSON in Swift

提交回复
热议问题