Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON parsing using NSJSONSerialization in iOS

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?

like image 759
Nayan Avatar asked Dec 05 '13 11:12

Nayan


3 Answers

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"];
like image 141
Suryakant Sharma Avatar answered Nov 05 '22 11:11

Suryakant Sharma


When you see braces like that, it represents an array, not a dictionary. Your JSON also shows that by enclosing the data in brackets ('[' and ']'). So:

RESPONSE =(
                {
            email = "[email protected]";
            id = 20;
            location = "31.000,71.000";
            phone = 1234567890;
            username = john;
        }
);

RESPONSE is an Array of Dictionaries. To access the data, iterate through the array:

for (NSDictionary *responseDictionary in [JSONDictionary objectForKey:@"RESPONSE"]) {
        NSString *name = [responseDictionary objectForKey:@"username"];
        .....
}

or grab a dictionary at an index:

NSDictionary *responseDictionary = [[JSONDictionary objectForKey:@"RESPONSE"] objectAtIndex:0];
NSString *name = [responseDictionary objectForKey:@"username"];

Whenever in doubt, log the the class:

NSLog(@"%@", [[dictionary objectForKey:@"key"] class]);

to see what is being returned from the dictionary.

like image 4
Chris Avatar answered Nov 05 '22 10:11

Chris


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

The NSLog of NSDictionary is based on the sorted keys.

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

RESPONSE =(
            {
        email = "[email protected]";
        id = 20;
        location = "31.000,71.000";
        phone = 1234567890;
        username = john;
    }
);

The RESPONSE is a key and the value is an NSArray. The array contains one NSDictionary object with keys as email, id, location, phone and username.

NOTE: () says array. {} says dictionary.

like image 3
Anoop Vaidya Avatar answered Nov 05 '22 12:11

Anoop Vaidya