need a Sample JSON parser in objective c - iphone

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

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.

Convert NSData to JSON

I have a NSData object, i need to convert it a NSDictionary object.
NSData *data = ....;
Now i need to convert this to a NSDictionary, How can i do this programatically ?
note: After i save the NSData to the NSDictionary i should be able to access key value pairs of the NSDictionary.
I don't have a code to demonstrate my workings so far, I have only created the NSData object, and have no clue to continue :)
You can subclass MKNetworkOperation and override the responseJSON method with the following:
-(id) responseJSON
{
NSString *rawJSON;
id jsonValue = nil;
if ((rawJSON = [[NSString alloc] initWithData:[self responseData] encoding:NSUTF8StringEncoding]) != nil) {
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
if ((jsonValue = [jsonParser objectWithString:rawJSON]) == nil) {
NSLog(#"This string doesn't seem to be JSON: '%#'\nraw Data : '%s'", rawJSON, (char *)[[self responseData] bytes]);
return [self responseString];
}
}
else {
NSLog(#"This data doesn't seem to be an UTF8 encoded string: %#", [self responseData]);
return [self responseString];
}
return jsonValue;
}
Please check this link of stack overflow, I have already consumed the JSON services, it will help you a lot. All of the coding is there.
JSON Data Conversion
And here is the tutorial with sample project
JSON Parse Tutorial
Hope you would find it helpful
I highly recommend invoking SBJSON framework, it saved my time for many times, exactly finished my work and easily to use. You don't need to know the details of the conversion algorithm, just download and invoke it.
You might want to download it from here, then follow this tutorial to get your things done.

How to use SBJSON parse with using Content-Type and Method(POST,GET) in iPhone?

Already i have worked on SBJSON parsing, that was working very fine. Now, i am working in SBJSON parsing. The problem is the parsing result is returning null(In NSDictionary). I have tested the url in Firefox POST tool, it returned result with the Content-Type = application/x-www-form-urlencoded and Method = POST. How to use Content-Type and Method[POST, GET] in SBJSON file parsing? Really i can not find the result in google search(sorry). Please help me to solve my problem. Please suggest me any sample code or idea. Thanks in advance.
This is my code,
SBJSON *jsonParser = [[SBJSON new] autorelease];
NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:#"SAMPLE URL"]];
NSString *stringUrl = [NSString stringWithFormat:#"%#",urls];
NSDictionary *dictionary = (NSDictionary *) [jsonParser objectWithString:stringUrl error:nil];
NSLog(#"Dictionary : %#", dictionary);
The dictionary is returning null. How to use Content-Type and [POST,GET] methods in SBJSON file parsing?
Thanks in advance.
You are not actually fetching the string data at the URL, just creating a URL and parsing that, which unsurprisingly, cannot be converted to a JSON object. You should asynchronously fetch the string data using something like NSURLConnection, or easier ASIHTTP, then parse the result.

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.

Extracting array from NSMutableData in http response

using iphone sdk 4.0. The callback for an http request gives data as an NSData object
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the data received to our data
[theData appendData:data];
}
In my php script on the server i am returning an array as follows
var_dump($array).
How do i get my array back from the NSMutableData object 'theData' obove on my iphone.
Thanks
You have a string describing your array (or maybe several arrays?) stored as a sequence of bytes in your NSMutableData object. In order to turn it back into an array you're going to need to parse the var_dump output, which is likely to be arduous.
If you can find a library (or roll your own code) to return your data in Apple plist format, your task will be much easier: you can use
[NSPropertyListSerialization propertyListFromData:mutabilityOption:format:errorDescription:]
which takes an NSData (or NSMutableData) pointer as its first argument. Try http://code.google.com/p/cfpropertylist/ for a starting point.
From the example code at the cfpropertylist page:
$plist = new CFPropertyList();
$td = new CFTypeDetector();
$guessedStructure = $td->toCFType( $array );
$plist->add( $guessedStructure );
// and then return the plist content with
$plist->toXML()
and in your iOS code:
NSString *errorString = nil;
NSArray *array = [[NSPropertyListSerialization
propertyListFromData:theData
mutabilityOption:NSPropertyListImmutable
format:nil
errorDescription:&errorString] retain];
I would likely use YAJL on iOS, and $var = json_encode($array); in the PHP. Then in the iOS, I would parse that content from the NSData input like:
YAJLParser *parser = [[YAJLParser alloc] initWithParserOptions:YAJLParserOptionsAllowComments | YAJLParserOptionsCheckUTF8];
parser.delegate = [[[MyArrayParserDelegate alloc] init] autorelease];
[parser parse:data];
NSArray *thePhpArrayReceived = parser.delegate.resultantArray;
Please check out how to structure the delegate, and get YAJL here : Get YAJL + Readme
PHP outputs text so you will have to read that NSData as NSString and then parse out the array data according to the format specified by var_dump. As a starting point, the following code snippet should print out the array (as text) to your console:
NSString * dump = [[NSString alloc] initWithData:theData
encoding:NSUTF8StringEncoding];
NSLog(#"%#", dump);
[dump release];
As Seamus Campbell points out, there are better ways of doing this. Another option would be to output XML from your PHP script, and then use Cocoa's XML parsing methods to retreive the array.