JSON Parsing in Swift 3

前端 未结 8 823
暖寄归人
暖寄归人 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

    0 讨论(0)
  • 2020-12-01 11:40
    dict = {
        message = "Login successfully.";
        status = 1;
        "user_details" =     (
                    {
                dob = "1900-11-18";
                email = "rizwan@gmail.com";
                gender = male;
                name = Rizwan;
                nickname = Shaikh;
                "profile_pic" = "1483434421.jpeg";
                "social_id" = "<null>";
                "user_id" = 2;
            }
        );
    }
    

    We can parse above json in Swift 3 as

    var dict2  = dict as! [String : Any]
    print(dict);
    let demoStr = dict2["message"] as! String
    print(demoStr)
    let demoArray = dict2["user_details"] as! [Any]
    let demoDict = demoArray[0] as! [String:Any]
    print(demoDict["dob"]!)
    
    0 讨论(0)
提交回复
热议问题