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.
Related
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);
}
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
While creating a login view on my iphone app, I ran into this error:
'NSInvalidArgumentException', reason: '-[SBJsonParser objectWithString:error:]:
unrecognized selector sent to instance 0x6695330'
It's coming from this line:
NSDictionary *results = [parser objectWithString:json_string error:nil];
From this method:
+ (BOOL)loginWithUsername:(NSString *)username password:(NSString *)password
{
NSString *urlString = [NSString stringWithFormat:#"%#login3", ROSE_ROOT_URL];
NSURL *url = [NSURL URLWithString:urlString];
NSString *requestString = [NSString stringWithFormat:#"&mobile=1&username=%#&password=%#", username, password];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSData dataWithBytes:[requestString UTF8String] length:[requestString length]]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
[request release];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON product objects
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *results = [parser objectWithString:json_string error:nil];
[json_string release];
[parser release];
// NSDictionary *results = [RoseFetcher fetch:request];
// [request release];
if ([[results objectForKey:#"password"] intValue] == 0)
return NO;
return YES;
}
Any help or explanation would be greatly appreciated.
According to the documentation for SBJsonParser, it doesn't have a method called -objectWithString:error: - an opinion that's corroborated by your findings at runtime. Try sending it a message it will respond to, like -objectWithString:.
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];
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.