Dealing with JSON on iPhone
You can easily use the JSON (JavaScript Object Notation) data format in client-server communications when writing an iPhone app. This blog is not suggesting that JSON is a more superior format for data exchange than its counterparts such as XML. In fact, we have many projects that don’t use JSON. However, handling JSON is relatively straight forward in ObjectiveC.
Unfortunately, Apple iPhone SDK (as of this writing, the latest is iPhone 2.2.1) doesn’t come with a built-in JSON parser. But I found out a good one called json-framework. It is both a generator and a parser. As a generator, json-framework can create JSON data from an NSDictionary. As a parser, you can pass to json-framework an NSString that consists of JSON data and it will return a NSDictionary that encapsulates the parsed data.
#import “JSON/JSON.h”
NSDictionary *requestData = [NSDictionary dictionaryWithObjectsAndKeys:
@”grio”, @”username”,
@”hellogrio”, @”password”,
nil];
NSString* jsonString = [requestData JSONRepresentation];
{“username”:”grio”,”password”:”hellogrio”}
SBJSON *json = [[SBJSON new] autorelease];
NSError *jsonError;
NSDictionary *parsedJSON = [json objectWithString:jsonResult error:&jsonError];
NSDictionary* menu = [parsedJSON objectForKey:@”menu”];
NSLog(@”Menu id: %@”, [menu objectForKey:@”id”]);
NSLog(@”Menu value: %@”, [menu objectForKey:@”value”]);
Menu id: file
Menu value: File
NSDictionary* popup = [menu objectForKey:@”popup”];
NSArray* menuItems = [popup objectForKey:@”menuitem”];
NSEnumerator *enumerator = [menuItems objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
NSLog(@”menuitem:value = %@”, [item objectForKey:@”value”]);
}
menuitem:value = New
menuitem:value = Open
menuitem:value = Close
8 Comments