parsing JSON response from server in same order in ios - iphone

i have an app which fetches JSON response from server. the JSON response from server looks as follows:
{"status":"SUCCESS","message":"XYZ","token":"ABCDEFGHIJ"}
now i need to store this in a NSDictionary for further parsing. so i use the following approach:
urldata1=[NSURLConnection sendSynchronousRequest:theRequest returningResponse:&res error:nil]; NSDictionary
*myDictionary=[NSJSONSerialization JSONObjectWithData:urldata1 options:NSJSONReadingMutableContainers error:nil];
}
but now the dictionary i get looks as follows:
{
message = "XYZ";
status = SUCCESS;
token = "ABCDEFGHIJ";
}
So i see that the dictionary has been sorted on the basis of keys... is there a way to reproduce the exact same response from server in my dictionary..

It doesn't matter in what order the NSDictionary is because you retrieve the object from the dictionary with keys.
So if you want to access the status first use this code
NSString *status = [myDictionary objectForKey#"status"];
NSString *message = [myDictionary objectForKey#"message"];
NSString *token = [myDictionary objectForKey#"token"];
And you can access a Dictionary inside a Dictionary like this
NSDictionary *dict= [myDictionary objectForKey#"SomeOtherDictionary"];

Sorting a dictionary is meaningless. You need to first create an array which will sort according to your needs.
You can refer Sorting NSDictionary from JSON for UITableView for further explanations.

Related

Parse json in objective-c for my iphone app

i have a problem parsing my json data for my iPhone app, I am new to objective-C. I need to parse the json and get the values to proceed. Please help. This is my JSON data:
[{"projId":"5","projName":"AdtvWorld","projImg":"AdtvWorld.png","newFeedCount":"0"},{"projId":"1","projName":"Colabus","projImg":"Colabus.png","newFeedCount":"0"},{"projId":"38","projName":"Colabus Android","projImg":"ColabusIcon.jpg","newFeedCount":"0"},{"projId":"25","projName":"Colabus Internal Development","projImg":"icon.png","newFeedCount":"0"},{"projId":"26","projName":"Email Reply Test","projImg":"","newFeedCount":"0"},{"projId":"7","projName":"PLUS","projImg":"7plusSW.png","newFeedCount":"0"},{"projId":"8","projName":"Stridus Gmail Project","projImg":"scr4.png","newFeedCount":"0"}]
On iOS 5 or later you can use NSJSONSerialization. If you have your JSON data in a string you can do:
NSError *e = nil;
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
Edit To get a specific value:
NSDictionary *firstObject = [jsonArray objectAtIndex:0];
NSString *projectName = [firstObject objectForKey:#"projName"];
I would recommend using JSONKit library for parsing.
Here's a tutorial on how to use it.
You will basically end up with a dictionary and use objectForKey with your key to retrive the values.
JSONKit
or
NSJSONSerialization(iOS 5.0 or later)
I have had success using SBJson for reading and writing json.
Take a look at the documentation here and get an idea of how to use it.
Essentially, for parsing, you just give the string to the SBJsonParser and it returns a dictionary with an objectForKey function. For example, your code might look something like:
NSDictionary* parsed = [[[SBJsonParser alloc] init] objectWithString: json];
NSString* projId = [parsed objectForKey:#"projId"];
Use SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *dicRes = [parser objectWithString:stringFromServer error:nil];
No need to use third party classes. Objective-c already includes handling JSON.
The class NSJSONSerialization expects an NSData object or reads from a URL. The following was tested with your JSON string:
NSString *json; // contains your example with escaped quotes
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments error:&error]
For more options with NSJSONSerialization see the documentation.

How To Parse JSON Format in Objective C

Hey every one i am programming an iphone app to get google search results 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 :
responseData
responseDetails
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.

How to divide the date from JSON output?

I am developing one application.In that i use the json.Json gives the output and that output is stored in one dictionary like
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *results = [responseString JSONValue];
So my problem is how to separate the data from results.I want to print the only city name.so please tell me how to extract the data from dictionary.
you need to see the response and by using objectForKey: (method in NSDictionary) you can find what ever you want. (pick data by their key).
Check NSDictionary. Use objectForKey: to retrive the data. The key will be your tag value.

Extracting specific part of JSON respose on iPhone

I'm looking at adding a distance calculator to my application. I have been looking at Google's API put i cant seem to decode the JSON. I have managed to do so with PHP. The code for that was:
substr($convertedtoarray['routes']['0']['legs']['0']['distance']['text'], 0, -3);
On the iPhone i managed to get the JSON response but can't get the specific part of it that I want.
Json address: http://maps.googleapis.com/maps/api/directions/json?origin=plymouth&destination=pl210bp&sensor=false
NSMutableDictionary *luckyNumbers = [responseString JSONValue];
[responseString release];
if (luckyNumbers != nil) {
NSString *responseStatus = [luckyNumbers objectForKey:#"routes"];'
}
Where would I go from here?
Any help would be great cheers
NSString *responseStatus = [[[[[[luckyNumbers objectForKey:#"routes"]objectAtIndex:0] objectForKey:#"legs"]objectAtIndex:0] objectForKey:#"distance"] objectForKey:#"text"];
Very ugly you can extract in separate objects like this:
NSArray *routesArray = [luckyNumbers objectForKey:#"routes"];
NSDictionary *firstRoute = [routesArray objectAtIndex:0];
NSArray *legsArray = [firstRoute objectForKey:#"legs"];
NSDictionary *firstLeg = [legsArray objectAtIndex:0];
NSDictionary *distanceDict = [firstLeg objectForKey:#"distance"];
NSString *distanceText = [distanceDict objectForKey:#"text"];
Good luck.
The easiest thing to do would be to create a dictionary iterator, and loop over what children the luckynumbers dictionary has, you can print out, or debug, to see what the keys for these children are, and what object types they are.
I used this technique a few times to figure out what the structure of an XML doc I was being returned was like.

enabling iPhone to fetch and parse JSON?

I don't know how to use the output=json;callback= for my iPhone App, appreciate for your help!
This URL at tw.money.yahoo.com returns this JSON:
{"ResultSet":{"totalResultsAvailable":"0",
"Error":{"Code":400,
"Message":"\u67e5\u8a62\u53c3\u6578\u4e0d\u5408\u6cd5"}
}
}
If you get the response as a string, then it's very simple to parse - it just gets turned into NSDictionary and NSArray objects :)
Get the touch-json framework from github.
NSString *myJsonString = #"{'name':'Bob'}";
NSDictionary *dict = [myJsonString JSONValue];
After calling JSONValue on a string, dict will contain the key "name" that has the value "Bob".
jsonkit
NSDictionary *listings = [[content objectFromJSONString] valueForKey:#"ResultSet"];