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

json_file

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

About the Author:

Cayden is a programmer that expertize in ios and PHP development.

6 Comments + Add Comment

  • 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

  • Superb blog post, trendy page theme, stick to the great work

  • Wow…, small world, I like your post.

Leave a comment

Ads

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Facebook Page

Categories