Aug 29, 2010

Objective-C Parse JSON String To Object




JSON is a data structure like a XML, but JSON file size in most situation is small than XML file. It is a importance point in the mobile network.

iPhone Cocoa Touch framework does not include JSON library, We need download third party library to parse the JSON data. I am recommend below JSON library in Objective C.

json-framework

This JSON library is very simple. See below tutorial to know how to use this library.


When you download complete and unzip the file. You need copy JSON folder into your project. Add #import "JSON.h" in you class when you need to parse JSON data.

#import "JSON.h"

OK, this tutorial have a JSON sample. (copy from http://www.json.org/example.html)
{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

I will put this JSON data into file, this file call data.json. Now, we are going to read this file and parse it to object.

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
NSString *jsonStr = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *json = [parser objectWithString:jsonStr error:nil];

NSDictionary *glossary = [json objectForKey:@"glossary"];
NSString *glossaryTitle = [glossary objectForKey:@"title"];

NSDictionary *glossDiv = [glossary objectForKey:@"GlossDiv"];
NSString *glossDivTitle = [glossDiv objectForKey:@"title"];

NSArray *glossSeeAlso = [[[[glossDiv objectForKey:@"GlossList"] 
objectForKey: @"GlossEntry"] 
objectForKey: @"GlossDef"] 
objectForKey: @"GlossSeeAlso"];

NSLog(@"Glossary Title: %@", glossaryTitle);
NSLog(@"GlossDiv Title : %@", glossDivTitle);

NSLog(@"GlossSeeAlso item 1: %@", [glossSeeAlso objectAtIndex:0]);
NSLog(@"GlossSeeAlso item 2: %@", [glossSeeAlso objectAtIndex:1]);

Line of 2 is put JSON string in to NSString.

Line of 4 is new a JSON parser.

Line of 5 is parse a JSON and convert it to NSDictionary, In this NSDictionary's object also parsed to other object, such as NSArray, NSString, etc...

Line of 7 is use "glossary" key to fetch object. This object include below content:
{
    "title": "example glossary",
    "GlossDiv": {
        "title": "S",
        "GlossList": {
            "GlossEntry": {
                "ID": "SGML",
                "SortAs": "SGML",
                "GlossTerm": "Standard Generalized Markup Language",
                "Acronym": "SGML",
                "Abbrev": "ISO 8879:1986",
                "GlossDef": {
                    "para": "A meta-markup language, used to create markup languages such as DocBook.",
                    "GlossSeeAlso": ["GML", "XML"]
                },
                "GlossSee": "markup"
            }
        }
    }
}

Line of 8 is use upper content and use "title" key to fetch data. "title" content is "example glossary". It is a string, so NSDictionary return NSString object.

Line of 13 use "GlossSeeAlso" key to fetch data. It is an array object, so NSDictionary return NSArray.

The final result:
2010-08-27 15:15:44.003 JSON[47655:207] Glossary Title: example glossary
2010-08-27 15:15:44.049 JSON[47655:207] GlossDiv Title : S
2010-08-27 15:15:44.050 JSON[47655:207] GlossSeeAlso item 1: GML
2010-08-27 15:15:44.050 JSON[47655:207] GlossSeeAlso item 2: XML

If your JSON data not store in the file. It stored on the server and via network to download, you can use below method to get JSON data.

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://pro.ctlok.com/data.json"]];

NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

NSString *jsonStr = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];


17 comments:

custom chrome rims said...

im feeling it

hmm...? said...

thanks

Online Casino said...

ha, I will try out my thought, your post give me some good ideas, it's really amazing, thanks.

- Thomas

Giupa said...

hi,
I tried your tutorial and it works. congratulations:)
I would like to adapt this tutorial to my app, which should make a parser of the data returned from this address: "http://ajax.googleapis.com/ajax/services/search/local?v=1.0&rsz=8&sll=41.23497, & q = 16.51413 restaurant.
I need only some areas of the json file.

thanks
by soon

Giupa said...

the right link is: http://ajax.googleapis.com/ajax/services/search/local?v=1.0&rsz=8&sll=41.23497,16.51413&q=ristorante

mietwagen mallorca said...

Very enlightening and beneficial to someone whose been out of the circuit for a long time.

- Kris

RedMango said...

Very nice post!

herbalife said...

Quite interesting Blog .. thanks a lot

livelybrowsers said...

Thanks for good stuff

weddingcaketoppershumorous said...

Thank you, I have recently been searching for information about this topic for long time and yours is the best I have discovered so far.

sunny said...

Awesome. I had gotten so frustrated with using json, this is the best tutorial. Thank you!!

Sherlene Ozer said...

Its like you read my mind You appear to grasp such a lot about this, such as you wrote the book in it or something. I suppose that you simply may do with some pics to drive the message home a bit, however apart from that, this is often great blog. an excellent read. unwell definitely be back.

JSON | Advanced App Development said...

[...] Objective-C Parse JSON String To Object This entry was posted in iOS Development. Bookmark the permalink. ← Accessorizer 2.7 [...]

Hari haran said...

thanks for this nice tutorial..........

Thanh nx said...

thanks

for IT the said...

JavaScript Online Training JavaScript Online Training JQuery Online Training JQuery Online Training
JavaScript Course | HTML5 Online Training

for IT the said...

Wow. This really made my day. Thanks a lot!

JavaScript Online Training | HTML5 Online Training JQuery Online Training JQuery Online Training Javascript Online Training

Angularjs Training in Chennai
JavaScript Training Courses | Javascript Online Training | Angular 2 Online Training

Post a Comment

Twitter Delicious Facebook Digg Google Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best Hostgator Coupon Code