4

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I will test it and accept this answer if it works! Thanks!
0

try this

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

1 Comment

Still the same, not working (I have added it to if clause)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.