how-to-use-json-in-cocoao-bjective-c

Using JSON in Cocoa is simple thanks to an excellent open-source JSON Framework by Stig Brautaset. The framework will decode a JSON string into native Objective-C objects, and vice versa . The project includes a packaged Framework, Mac and iPhone SDKs, as well as the source code. The easiest method is to directly embed the source in your app as it’s pretty lightweight, and will work on both Mac and iPhone apps. Here are step-by-step instructions on how to use JSON in your app. 

 

1.) Download the latest version (currently 2.2.1) from https://github.com/stig/json-framework/downloads

 Version 3.1 requires Xcode 4.2 to build, because previous versions did not have ARC support. If you can't use Xcode 4.2, or for some reason can't use ARC, you need to stick with SBJson version 3.0.

 

Installation

The simplest way to start using JSON in your application is to copy all the source files (the contents of the Classes folder) into your own Xcode project.

  1. In the Finder, navigate to the $PATH_TO_SBJSON/Classes folder and select all the files.
  2. Drag-and-drop them into your Xcode project.
  3. Tick the Copy items into destination group's folder option.
  4. Use #import "Json.h" in your source files.

 

Here’s an example showing how to download the public timeline from Twitter as JSON and parse it.

// Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];

// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://twitter.com/statuses/public_timeline.json"]];

// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];

// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
  // You can retrieve individual values using objectForKey on the status NSDictionary
  // This will print the tweet and username to the console
  NSLog(@"%@ - %@", [status objectForKey:@"text"], [[status objectForKey:@"user"] objectForKey:@"screen_name"]);
}

 

实战经验:下载的版本为JSON v2.3.2 (iOS)

SBJSON *parser = [[SBJSON alloc] init];

改为 SBJsonParser *parser = [[SBJsonParseralloc] init];

 项目截图:

 

http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c

 
posted @ 2012-07-04 11:50  Season2009  阅读(254)  评论(0编辑  收藏  举报