Uncategorized

Objective-C Parse JSON String To Object

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];