ƒernando Valle
ƒernando Valle

Reputation: 3714

How can I parse array JSON in objective-c

I did it easily in Android but Im little lost how to do it in iOs. My json is like:

[{"name":"qwe","whatever1":"asd","whatever2":"zxc"}, 
{"name":"fgh","whatever1":"asd","whatever2":"zxc"}]

If I do:

NSData *jsonData = [data dataUsingEncoding:NSUTF32BigEndianStringEncoding];

rows  = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: &error];

in rows can I access with?

NSString *name = [[rows objectAtIndex:0] [objectForKey:@s"name"]];

Or how I do that? thanks.

FINALLY NSString *name = [[rows objectAtIndex:0] objectForKey:@"name"]]; WORKS! :D

Upvotes: 3

Views: 3899

Answers (3)

zaph
zaph

Reputation: 112857

Assuming the NSJSONSerialization operation was successful, simply:

NSString *name = rows[0][@"name"];

NSUTF32BigEndianStringEncoding is suspicious, json data is more usually NSUTF8StringEncoding.

Upvotes: 2

Kalpesh
Kalpesh

Reputation: 5334

NSMutableArray *row= [NSJSONSerialization JSONObjectWithData: jsonData options:        NSJSONReadingMutableContainers error: &error];
        for (int i=0; i<[row count]; i++) {
            NSMutableDictionary *dict=[row objectAtIndex:i];;
            NSString * name=[dict valueForKey:@"name"];
            NSLog(@"%@",name);
        }
    }

Upvotes: 2

trojanfoe
trojanfoe

Reputation: 122391

I think that will work, however you want:

NSString *name = [[rows objectAtIndex:0] objectForKey:@"name"];

(dropped extraneous square brackets and use @"name" as string literal).

However, is the input JSON really in UTF-32 format?

Upvotes: 3

Related Questions