JSON parsing using NSJSONSerialization in iOS

Nayan picture Nayan · Dec 5, 2013 · Viewed 28.3k times · Source

I am parsing a JSON in my code. But I am getting some unexpected issues while retrieving data of parsed JSON. So let me explain my problem.

I have to parse following JSON data using xcode. This is what data to be parsed looks like while I hit same URL in browser:

{
"RESPONSE":[
    {"id":"20",
    "username":"john",
    "email":"[email protected]",
    "phone":"1234567890",
    "location":"31.000,71.000"}],
"STATUS":"OK",
"MESSAGE":"Here will be message"
}

My code to reach up to this JSON data is as follow:

NSData *data = [NSData dataWithContentsOfURL:finalurl];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

If I print object json using NSLog, i.e. NSLog(@"json: %@", [json description]); it looks like:

json: {
    MESSAGE = "Here will be message";
    RESPONSE =(
                {
            email = "[email protected]";
            id = 20;
            location = "31.000,71.000";
            phone = 1234567890;
            username = john;
        }
    );
    STATUS = OK;
}

So, here I observed two things:

  1. Sequence of keys (or nodes) (MESSAGE, RESPONSE and STATUS) is changed as compared to web response above.

  2. The RESPONSE is get enclosed in '(' & ')' braces.

Now if I separate out values for keys MESSAGE & STATUS and NsLog them, then they get printed as proper string.

Like msgStr:Here will be message & Status:OK

But if I separate out value for RESPONSE as a dictionary and again separating sub values of that dictionary like email and username, then I can't getting those as string.

Here is the code so far I wrote:

NSMutableDictionary *response = [json valueForKey:@"RESPONSE"];
NSString *username = [response valueForKey:@"username"];
NSString *emailId = [response valueForKey:@"email"];

If I print username and emailId, then they are not getting printed as normal string, instead it outputs as:

username:(
    john
)

email:(
    [email protected]
)

So my question is why it's not getting as a normal string? If I tried to use this variables further then they show value enclosed within '(' & ')' braces. Is this happening because of NSJSONSerialization?

Answer

Suryakant Sharma picture Suryakant Sharma · Dec 5, 2013

First of all in your JSON response dictionary, under the key 'RESPONSE' you have a array not a dictionary and that array contains dictionary object. So to extract username and email ID so as below

NSMutableDictionary *response = [[[json valueForKey:@"RESPONSE"] objectAtIndex:0]mutableCopy];
 NSString *username = [response valueForKey:@"username"];
 NSString *emailId = [response valueForKey:@"email"];