开发者

How To Parse JSON Format in Objective C

开发者 https://www.devze.com 2023-04-10 01:45 出处:网络
Hey every one i am programming an iphone app to get google search res开发者_如何学Pythonults into my app ,,, i have used the JSON Class to get the result ... when i parsed it in JSON Parser and store

Hey every one i am programming an iphone app to get google search res开发者_如何学Pythonults into my app ,,, i have used the JSON Class to get the result ... when i parsed it in JSON Parser and store it in NSDictionary i got 3 keys :

  1. responseData
  2. responseDetails
  3. responseStatus

the important one is the first one responseData which is has the search results ...

the problem that there is (i think) another key within responseData which is "results" which contains the urls and other stuffs which is the most important part for my app... how to access this one and put it into NSDictionary .....

this is the request :

http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton

and to make things clear please consider to put that request into your browser and when you get the results copy it and put it in this website at the left side to see what the keys and other things:

http://json.parser.online.fr/

thnx


You could use JSON parser - SB Json to convert json string into ObjectiveC objects. Note that there are a number of JSON parsers available in ObjectiveC but I chose SB Json for it's ease of usage. But according to some benchmarks JSONKit is faster than SBJson.

Once you have your json string use this like so -

#import "JSON.h"

// Create SBJSON object to parse JSON
SBJSON *parser = [[SBJSON alloc] init];

// parse the JSON string into an object - assuming json_string is a NSString of JSON data
NSDictionary *object = [parser objectWithString:json_string error:nil];
NSLog(@"JSON data: %@", object);

Here's what you would do if you needed to parse public timeline from Twitter as JSON.The same logic could be applied to your Google Search results. You need to carefully inspect your json structure that's all...

// 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"]);
}


Il me semble que vous savez déjà comment analyser JSON en forme NSDictionary, alors voici quelques suggestions sur la façon de forer vers le bas pour vos résultats détaillés en cascade. En anglais pour tout le monde.

responseData itself is an NSDictionary and results is an object within it. Results happens to be an array for the case you gave.

After you convert the JSON to NSDictionary form, you will have recursively converted all of the objects inside.

You might try something like this to get at what you are looking for:

Lets assume the the fully converted JSON is in a NSDictionary called response

NSDictionary *responseDate = [response objectForKey:@"responseData"];
NSArray *resultsArray = [responseData objectForKey:@"results"];

Now you can use an iterator or a for-loop to go through each result.

One word of caution is that if there is only one result, you should first test to see if the class of the object is NSArray. Also, if there are no results, you should test for that too.

So you may want to code it this way to handle these cases:

NSDictionary *responseDate = [response objectForKey:@"responseData"];
If ([[responseData objectForKey:@"results"] isKindOfClass [NSArray class]]) {
    NSArray *resultsArray = [responseData objectForKey:@"results"];
    ... do other things to get to each result in the array ...
}
else if ([[responseData objectForKey:@"results"] isKindOfClass [NSDictionary class]]) {
    // it looks like each individual result in returned in a NSDictionary in your example
    ... do the things to handle the single result ...
}
else {
    // handle no results returned
}


The first thing you should do, if you do not understand exactly what's going on, is to NSLog the description of the JSON parser output. This will be a "nest" of NSDictionary and NSArray, and when you see the description output you will understand that there is a one-to-one mapping of JSON "object" to NSDictionary and JSON "array" to NSArray. So you "understand" the parser output the same way you "understand" the JSON source.

In your case you'd likely extract the "responseData" object, cast it to an NSDictionary, extract "results" from that, cast it (guessing here) to an NSArray, then iterate through that array to extract your individual results.

0

精彩评论

暂无评论...
验证码 换一张
取 消