Question

I created a WCF service, which provides the following response to my POST operation:

"[{\"Id\":1,\"Name\":\"Michael\"},{\"Id\":2,\"Name\":\"John\"}]"

My call to JSONObjectWithData, doesn't return any error, yet I can't enumerate over the results, what am I doing wrong?

NSError *jsonParsingError = nil;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];

NSLog(@"jsonList: %@", jsonArray);

if(!jsonArray)
{
    NSLog(@"Error parsing JSON:%@", jsonParsingError);
}
else
{
    // Exception thrown here.        
    for(NSDictionary *item in jsonArray)
    {
        NSLog(@"%@", item);
    }
}
Was it helpful?

Solution

As Jeremy pointed out, you shouldn't escape the quotes in the JSON data. But also, you've quoted the return string. That makes it a JSON string, not an object, so when you decode it you've got a string, not a mutable array, which is why you get an error when you try to fast iterate... you're not able to fast iterate over a string.

Your actual JSON should look like: [{"Id":1,"Name":"Michael"},{"Id":2,"Name":"John"}]. No quotes, no escapes. Once you eliminate the quotes around your JSON object, your app won't crash anymore, but then you're going to get a JSON deserialization error for malformed data (the escapes).

OTHER TIPS

The likely cause is you are using the wrong foundation object. Try changing NSMutableArray to NSDictonary.

From:

NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];

To:

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];

Parsing with NSJSONSerialization is easy, but I have also created a little framework that allows parsing JSON values directly into class objects, instead of dealing with dictionaries. Take a look, it might be helpful: https://github.com/mobiletoly/icjson

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top