unable to parse json response from google - iphone

I am trying to parse Json response from This URL. I have used SBJsonParser, MTJSON and another parser but i am getting NULL in all three case.
apiUrlStr = #"http://maps.google.com/maps?output=dragdir&saddr=Delhi&daddr=Mumbai+to:hyderabad";
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSUTF8StringEncoding error:nil];
SBJsonParser *json = [[[SBJsonParser alloc] init] autorelease];
NSDictionary *dictionary = [json objectWithString:apiResponse];
NSLog(#"dictionary=%#", [json objectWithString:apiResponse]);
2011-12-09 16:59:01.226 MapWithRoutes[2523:207] dictionary=(null)
Plz suggest me something

Oke if checked the url you gave with JSONlint.com and the JSON is not valid. thus can not be parsed by any library.
If you used JSONkit you can supply a NSError object with the parse call to see what went wrong:
NSError *error = nil;
NSDictionary *dictionary = [apiResponse objectFromJSONStringWithParseOptions:JKParseOptionNone error:&error];
if (!dictionary) {
NSLog(#"Error: %#", error);
}

Related

unable to access JSON data in Objective-C

Ok, this is my first approach to JSONs in Objective-C (and i'm quite new to the last one too). i'm to get infos stored my json to use them in Objective-C, but when trying to load it i get null in response from NSLog(#"%#",allData); on. Can anybody please tell me what i am doing wrong? thanks in advance for your time and your patience.
oh and if needed here's the json:
http://jsonviewer.stack.hu/#http://conqui.it/ricette.json
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"recipes" ofType:#"json"];
NSError *error = nil;
NSMutableData *JSONData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error];
NSLog(#"%#",JSONData);
NSArray *allData = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:nil];
NSLog(#"%#",allData);
for (NSDictionary *diction in allData) {
NSString *recipe = [diction objectForKey:#"recipe"];
[array addObject:recipe];
}
NSLog(#"%#",array);
The JSONObjectWithData method has an error parameter, of which you can avail yourself in order to diagnose the problem. For example:
NSError *error = nil;
NSArray *allData = [NSJSONSerialization JSONObjectWithData:JSONData
options:0
error:&error];
if (error)
NSLog(#"%s: JSONObjectWithData error: %#", __FUNCTION__, error);
In your comments, you suggest that you received an error about "Unescaped control character around character 414." That would suggest an error in the JSON, itself, which you might want to validate by copying into http://jsonlint.com/ and see if it reports any issues.
In response to the broader question about whether there are any Objective-C issues, there are no coding errors, per se. I can't comment on the for loop which clearly assumes that allData is an array of dictionaries to which I cannot attest without seeing the JSON. But I'll take your word for it. But, yes, the Objective-C code looks fine (albeit, a little light on checking of the return values types and error objects).
For example, if you wanted some diagnostic assert statements that you could use during development, you might do something like:
NSArray *allData = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:nil];
NSAssert(error, #"%s: JSONObjectWithData error: %#", __FUNCTION__, error);
NSLog(#"%s: array=%#", __FUNCTION__, array);
NSAssert([allData isKindOfClass:[NSArray class]], #"allData is not an array");
for (NSDictionary *diction in allData) {
NSAssert([diction isKindOfClass:[NSDictionary class]], #"%s: diction is not a dictionary (%#), __FUNCTION__, diction);
NSString *recipe = [diction objectForKey:#"recipe"];
NSAssert(recipe, #"%s: Did not find recipe key in diction (%#)", __FUNCTION__, diction);
[array addObject:recipe];
}
If any of these errors were possible runtime errors in production, you'd replace assert statements with if statements that do the necessary error handling. But hopefully it illustrates the concept.
Problem in your response is that , string values are unable to concatenate.So, I have to manually remove those tabs and new lines.
At five places you are getting error i.e:
pelate.
pasta.
pomodoro.
saporiti).
\t
- (void)viewDidLoad
{
NSString *urlStr=[NSString stringWithFormat:#"http://www.conqui.it/ricette.json"];
urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *fileNameURL=[NSURL URLWithString:urlStr];
NSLog(#"url is %#",urlStr);
NSMutableURLRequest *filenameReq=[[NSMutableURLRequest alloc] initWithURL:fileNameURL];
NSData *responseData=[NSURLConnection sendSynchronousRequest:filenameReq returningResponse:nil error:nil];
NSString *responseString=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
responseString=[[responseString componentsSeparatedByString:#"\n"] componentsJoinedByString:#""];
responseString=[responseString stringByReplacingOccurrencesOfString:#"\t" withString:#""];
responseData=[responseString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"response String is %#",responseString);
[NSCharacterSet characterSetWithCharactersInString:responseString];
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: 0 error: &e];
NSLog(#"JSON Array is %# & error is %#",jsonArray,e);
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

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);
}

Wunderground API json lookup on iPhone

Never touched json before. I'm trying to access some variables within the Wunderground weather API for Melbourne. For example, let's say I want to access the "wind_dir":"East" variable. This is my code thus far:
NSString *urlString =
[NSString stringWithFormat:
#"http://api.wunderground.com/api/key/geolookup/conditions/forecast/q/-33.957550,151.230850.json"];
NSLog(#"URL = %#", urlString);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *weatherInfo = [parser objectWithString:json_string error:nil];
for (NSDictionary *weatherString in weatherInfo)
{
NSLog(#"some weather info = %#", [[[weatherString objectForKey:#"response"] objectForKey:#"current_observation"] objectForKey:#"wind_dir"]);
}
My code reaches the for loop and crashes with this error: -[NSCFString objectForKey:]: unrecognized selector sent to instance.
I'm not 100% sure what's causing the crash, and whether my path to the "wind_dir" variable is correct, though they could well be the same problem.
Thanks in advance for any help.
either the "response" property or the "current_observation" propery is string and not dictionary.
the error you are getting is that you are trying to call "objectForKey" on a string.
after looking at the result of the API, it seems that you are not getting an array.
You should do something like this:
NSDictionary *weatherInfo = [parser objectWithString:json_string error:nil];
NSLog(#"some weather info = %#", [[weatherInfo objectForKey:#"current_observation"] objectForKey:#"wind_dir"]);
instead of your for statement.

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];

Encoding Problem in iphone

Below is my code..
NSString *strResponce = [[NSString alloc] initWithData:JsonData encoding:NSASCIIStringEncoding];
here string has some data.
[JsonData release];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
ArrayWebContent=[json objectWithString:strResponce error:&error];
But array is null.
any suggestion....
check your json data first put the content of the string strResponce in to the url
Checking json data are proper for parsing
if it gonna generate the parse error than you should check the content of the ws as it may content special charactor for which iphone can not support parsing
good luck
Try with below functions.
- (id) objectWithUrl:(NSURL *)url
{
SBJSON *jsonParser = [SBJSON new];
NSString *jsonString = [self stringWithUrl:url];
// Parse the JSON into an Object
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSString *)stringWithUrl:(NSURL *)url
{
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
Let me know for any difficulty.