21
2011
JSON in ios 5
Before ios 5, we have to use third party JSON library like SBJSON or TouchJson to deal with JSON data. Today, iOS 5 has built-in APIs in the Foundation Framework which is called the NSJSONSerialization to make it easy to read and write JSON. Click here for reference.
Below is an example of how to read JSON data into NSArray, NSDictionary and NSString.
NSString* str= @"{\"name\":\"cayden\",\"hobby\":[{\"0\":\"programming\"}, {\"1\":\"gym\"}]}"; NSData* data=[str dataUsingEncoding:NSASCIIStringEncoding]; NSError* error; NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; NSString *name = [json objectForKey:@"name"]; NSArray *hobby = [json objectForKey:@"hobby"]; NSLog(@"name = %@, hobby = %@ & %@", name, [[hobby objectAtIndex:0] objectForKey:@"0"], [[hobby objectAtIndex:1] objectForKey:@"1"]);
In this example, I’ve created a dummy JSON data with 2 objects which are “name” and “hobby”, the “name” has a string value while the “hobby” has an array of 2 items. Since the NSJSONSerialization read in NSData, i convert the NSString to NSData. The data parsing is then done by the method:
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
That’s it, you can access the JSON data in NSArray, NSDictionary or NSString format base on the JSON structure. If you run the code, you should be able to see something in the console like below:
name = cayden, hobby = programming & gym
You can get the source code here. Try it out, have fun!
Related Posts
6 Comments + Add Comment
Leave a comment
Ads
Facebook Page
Categories
- Apache (1)
- Apps (2)
- Blog (19)
- IOS (20)
- IOS Library (5)
- iPhone Tutorial (17)
- Javascript (1)
- Node.js (1)
- Twitter (1)

An article by






Big addict on this page, a large number of your writes have really helped me out. Looking towards up-dates!
I found your website through a random stroke of luck. It helped me do my research on this topic. I have spent lots of time looking through your site. You have something good going here, keep it up!
Heart Healthy Recipes
thanks!
Superb blog post, trendy page theme, stick to the great work
Wow…, small world, I like your post.
lol