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"];
Related
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.
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.
I have an IPhone application in which i am using this code .
NSPropertyListFormat plistFormat;
NSDictionary *payloadDict = [NSPropertyListSerialization
propertyListWithData:subscriptionProduct.receipt
options:NSPropertyListImmutable
format:&plistFormat
error:nil];
where i am getting the subscriptionProduct.receipt correctly and reciept is an nsdata, which is declared inside the subscriptionProduct class.But after the conversion when i am trying to print payloadDict it is terned to be null.can anybody help me
Try getting the error out of the method and displaying it:
NSPropertyListFormat plistFormat;
NSError *parseError;
NSDictionary *payloadDict = [NSPropertyListSerialization
propertyListWithData:subscriptionProduct.receipt
options:NSPropertyListImmutable
format:&plistFormat
error:&parseError];
NSLog(#"payloadDict = %#", payloadDict);
NSLog(#"parseError = %#", parseError);
If parseError is nil, the property list serialization thinks it read the data properly. If not, its contents should tell you where to look.
Your comments seem to say that you want to construct a new NSDictionary that stores the object subscriptionProduct.receipt.
You can do this:
NSMutableDictionary *payloadDict = [NSMutableDictionary dictionary];
// Always check if values are nil before adding them to a dictionary.
if (subscriptionProduct.receipt)
[payloadDict setObject:subscriptionProduct.receipt forKey:#"receipt"];
If you want to load the receipt later, you can do this:
NSData *receiptData = [payloadDict objectForKey:#"receipt"];
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.
I want to know to parse a json object in objective C. I got the JSON object by loading a url. Can u please tell me how to do it or any samples or any reference.
The following is the sample json.
{
"name":"WFNX",
"now":
{
"id":"17749528",
"song":"Back Down South",
"artist":"Kings Of Leon"
},
"desc":"101.7 - True Alternative",
"audiostream":"http:\/\/www.streamaudio.com\/stations \/asx\/wfnx_fm.asx",
"genre":"Rock",
"tz":"EST",
"id":"17880",
"yes":"station"
}
Checkout this JSON framework for Objective-C on code.google.com or on Github.
It is pretty straightforward to use. You instantiate your SBJSON object then call objectWithString with your buffer:
SBJSON * parser = [[SBJSON alloc] init];
NSString * buffer = #"{"name":"WFNX"}";
NSError* error = NULL;
// the type of json will depend on the JSON data in buffer, in this case, it will be
// and NSDictionary with one key/value pair "name"->"WFNX"
id json = [parser objectWithString:buffer error:&error];
There are a few out there, see:
http://code.google.com/p/json-framework/
http://github.com/schwa/TouchJSON
for a big list:
http://www.json.org/
is a great reference site for JSON
I'm using YAJLiOS parser,not bad and compatable with ARC, here's documentation
http://gabriel.github.com/yajl-objc/
and parser itself on github
https://github.com/gabriel/yajl-objc
ex.
NSData *JSONData = [NSData dataWithContentsOfFile:#"someJson.json"];
NSDictionary *JSONDictionary = [tempContainer yajl_JSON];
and getting objects by objectForKey method or valueFoKey method if you need an array