Swift 2 parse Json as Optional to array

十年热恋 提交于 2020-01-14 10:45:09

问题


I am getting list of countries from a web service. After receiving it I used this code to process it:

if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
    // triggering callback function that should be processed in the call
    // doing logic
} else {
    if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? AnyObject {
       completion(json)
    } else {
       let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)                          
       print("Error could not parse JSON string: \(jsonStr)")
    }
}

And after that list looks like this (it ends up in this part NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? AnyObject) :

 Optional((
            {
            "country_code" = AF;
            "dial_code" = 93;
            id = 1;
            name = Afghanistan;
        },
            {
            "country_code" = DZ;
            "dial_code" = 213;
            id = 3;
            name = Algeria;
        },
            {
            "country_code" = AD;
            "dial_code" = 376;
            id = 4;
            name = Andorra;
        }
))

I should now convert this json object to array (or NSDictionary somehow) and to loop through it. Can someone advice how?


回答1:


Currently you can't loop through your object because it has been cast as AnyObject by your code. With your current code you're casting the JSON data either as? NSDictionary or as? AnyObject.

But since JSON always start with a dictionary or an array, you should do this instead (keeping your example):

if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
    // process "json" as a dictionary
} else if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? NSArray {
    // process "json" as an array
} else {
    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)                          
    print("Error could not parse JSON string: \(jsonStr)")
}

And ideally you would use Swift dictionaries and arrays instead of Foundation's NSDictionary and NSArray, but that is up to you.




回答2:


try this

let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]


来源:https://stackoverflow.com/questions/33509167/swift-2-parse-json-as-optional-to-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!