mservidio
mservidio

Reputation: 13057

NSJSONSerialization parsing response data

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

Upvotes: 1

Views: 6488

Answers (3)

interrupt
interrupt

Reputation: 2070

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

Upvotes: 0

Jason Coco
Jason Coco

Reputation: 78393

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).

Upvotes: 3

Jeremy
Jeremy

Reputation: 9030

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];

Upvotes: 3

Related Questions