I send some data to a webservice, it returns some JSON as NSData. How to convert to Dict?(iOS 4.3) - iphone

I send some credentials to a web-service.
I can get the responce as NSData or as an NSString.
Whats the simpleist way to convert the (NSData or NSString)JSON to a NSDictionary so I can process it?
Building for iOS4.3
Many Thanks,
-Code

From iOS 5.0 and on you can use NSJSONSerialization, docs here.
There is a good tutorial on how to use it, here.

Download SBJsonParser Framework using the link, http://github.com/stig/json-framework/downloads and add required classes to your project (SBJsonParser.h).
Import SBJsonParser.h and use the following code,
SBJsonParser *parser = [[SBJsonParser alloc] init];
//dictionary with name,id
NSDictionary *jsonObject = [parser objectWithString:jsonString error:NULL];
//name array
NSMutableArray *nameArray = [[NSMutableArray alloc]init];
for (NSMutableDictionary *dic in jsonObject){
[nameArray addObject:[dic valueForKey:#"name"]];
}

Use this :
NSString *urlString = [NSString stringWithFormat:kURLString,self.chapter,self.page];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[urlString dataUsingEncoding:NSISOLatin1StringEncoding]];
NSData* responseData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSISOLatin1StringEncoding];
NSDictionary* result = [(NSDictionary*)[responseString JSONValue] objectForKey:#"Result"];

I use SBJson
NSArray *arrObj = (NSArray*)[[JsonParser sharedJsonParser] getObjectsFromJsonString:responseString];
response string is a JSON string here

Related

Parsing XML String From WebServer

Alright, so here's where I'm at with my app.
I've got some code that connects to a remote server and grabs some XML data, and forms it into a string. Here is the code below:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *accept = [NSString stringWithFormat:#"application/xml"];
[request addValue:accept forHTTPHeaderField: #"Accept"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString* responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"%#",responseString);
Which returns
That's exactly the information I want. My question is how I can get the double value out of the gold brackets and into my application to use.
Thanks a lot!
There are a lot of tutorials of how to use NSXMLParser. For example, ray wenderlich or here and here.
There's quite a few XML parsing options available - ranging from libxml2, to NSXMLParser and a host of open-source projects.
One of my favorite XML parsers is RaptureXML, which can be installed via CocoaPods.
I like to create a category on RXMLElement to parse as follows:
- (PFCurrentConditions*)asCurrentCondition
{
NSString* summary = [[self child:#"weatherDesc"] text];
PFTemperature* temp = [PFTemperature temperatureWithFahrenheitString:[[self child:#"temp_F"] text]];
NSString* humidity = [[self child:#"humidity"] text];
NSString* wind =
[NSString stringWithFormat:#"Wind: %# km %#", [[self child:#"windspeedKmph"] text], [[self child:#"winddir16Point"] text]];
NSString* imageUri = [[self child:#"weatherIconUrl"] text];
return [PFCurrentConditions conditionsWithSummary:summary temperature:temp humidity:humidity wind:wind imageUrl:imageUri];
}
So, you can then use it as follows:
RXMLElement* rootElement = [RXMLElement elementFromXMLData:response.responseData];
__autoreleasing PFWeatherReport* weatherReport = [rootElement asWeatherReport];
Again, this is one of countless options, but my personal favorite.

json return to the format

Api Address:
http://suggest.taobao.com/sug?area=etao&code=utf-8&callback=KISSY.Suggest.callback&q=iphone
return:
KISSY.Suggest.callback({"result": [["iphone4s", "9809"], ["iphone5", "13312"], ["iphone4 手机", "69494400"], ["iphone5 港行", "14267"], ["iphone5三网", "2271160"], ["iphone4手机壳", "6199679"], ["iphone 5手机壳", "2527284"], ["iphone 5 保护壳", "5727586"], ["iphone 4贴膜", "147271"], ["iphone5壳", "2628540"]]})
NSURL * url = [NSURL URLWithString:#"http://suggest.taobao.com/sug?area=etao&code=utf-8&callback=KISSY.Suggest.callback&q=iphone"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSHTTPURLResponse* urlResponse = nil;
NSError * error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSData *date = [NSData alloc]init
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
// NSMutableArray *array=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
NSMutableArray *array = [jsonParser objectWithData:responseData];
NSLog(#"%#",array);
this array is null. i dont know the reason.
as i refer you request URL ,it has callback in it, if you keep it, it will not return you json as response, so remove "&callback=KISSY.Suggest.callback" from your URL
// Make sure you have include SBJSON files in your Project, as well you have imported header in your View Controller
#import "JSON.h"
// your request URL
NSURL * url = [NSURL URLWithString:#"http://suggest.taobao.com/sug?area=etao&code=utf-8&q=iphone"];
// URL Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSHTTPURLResponse* urlResponse = nil;
NSError * error = nil;
// initiate Request to get Data
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
// Encode your Response
NSString *content = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSUTF8StringEncoding];
// Now read a Dictionary from it using SBJSON Parser
NSDictionary *responseDict = [content JSONValue];
NSLog(#"Response [%#]",responseDict);
I'm not familiar with the SBJsonParser, but the format of the returned string looks like JSONP, not JSON. I would imagine simply cleaning out the wrapper call would get you what you are after.
Also, note that the 'root' of your response is a dictionary, not an array.
{"result": [[...
means that the code might should look like this:
NSDictionary *response = //... decode
NSArray *results = [response objectForKey:#"result"];
Edited
You just need to use http://suggest.taobao.com/sug?area=etao&code=utf-8&q=iphone instead of http://suggest.taobao.com/sug?area=etao&code=utf-8&callback=KISSY.Suggest.callback&q=iphone you own code will work..

Not getting json response in google query of longitude and latitude in iOS?

I am new to iOS, so if any help it will be appreciated.
I am trying to get the longitude and latitude from address, earlier the code was working fine but now the JSON data are coming null.
Here my sample code,
url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false",appDelegate.sAddress];
url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Address URL: %#",url);
//Formulate the string as a URL object.
NSURL *requestURL=[NSURL URLWithString:url];
NSData* data = [NSData dataWithContentsOfURL: requestURL];
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"my Coordinate : %#",returnString);
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
But i am getting the output as null.
So please help me out.
Thanks!
Thanks for your replies that all make me learn a lots.
As one of my friend just tell me the solution so i am sharing with you.
Here is the code,
url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false",appDelegate.sAddress];
url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Address URL: %#",url);
//Formulate the string as a URL object.
NSURL *requestURL=[NSURL URLWithString:url];
NSData* data = [NSData dataWithContentsOfURL: requestURL];
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *locationResult = [parser objectWithString:returnString];
//[reverseGeoString copy]`
And its working fine.
But still there is a question that why this happen.As earlier that code is working fine but it suddenly stopped working.
You must construct your returnString in the following method that actually receives the data:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
Check out this for additional information on how to use NSURLConnection and the delegate methods.
I would say you're missing the all-important "REQUEST"...
This is what I do. Hope it helps:
NSString *encodedAddress = (__bridge_transfer NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge_retained CFStringRef)searchBar.text, NULL, (CFStringRef) #"!*'();:#&=+$,/?%#[]",kCFStringEncodingUTF8 );
NSString* searchURL = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true",encodedAddress];
NSError* error = nil;
NSURLResponse* response = nil;
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSURL* URL = [NSURL URLWithString:searchURL];
[request setURL:URL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:30];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error){
NSLog(#"Error performing request %#", searchURL);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (jsonString!=nil){
NSLog(#"%#",jsonString);
}

Use of undeclared identifier in json for iOS

I am getting a use of undeclared identifier error in my json but I am following the example from http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c
how do I fix this? Yes I am very new to objective-c \ ios :) Thanks
I am putting this code in my view based application in my viewcontroller.m file
The issue is with "SBJSON *parser = [[SBJSON alloc] init];"
// 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"]);
}
Try changing the line to SBJsonParser *parser = [[SBJsonParser alloc] init];
Edit:
A way that can be easier is to use the NSString category that SBJSON provides:
NSArray *statuses = (NSArray *)[json_string JSONValue];

JSON parsing error

I am trying to parse some JSON. I've passed a constant key value and a string - butI'm receivng 16 objects in the statuses array and 20 objects in ststuses1.
Are any of the parsing steps wrong?
I have included the code for the JSON parser.
Thanks in advance.
SBJSON *parser = [[SBJSON alloc] init];
NSString *urlString =[NSString stringWithFormat:#"http://api.shiki.com/api/serch?key=%#&q=%#",apiKey, string];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSMutableArray *statuses = nil;
statuses = [[NSMutableArray alloc]init];
statuses = [parser objectWithString:json_string error:nil];
NSMutableArray *statuses0 = [[statuses valueForKey:#"offers"] valueForKey:#"offer"];
NSLog(#"Array Contents: %#", statuses0);
I guess that's not the only syntax-error in your code...
Please define statuses and ststuses1. I can only see statuses (redefined 2 times) and statuses0. Also please post a sample of the json-data you're parsing so I can take a look at it.