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];
Related
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
I just test the face.com face recognition api and I have success with json requests:
NSString *url = #"http://api.face.com/faces/detect.json?api_key=myapi&api_secret=mysecret&urls=http://userserve-ak.last.fm/serve/_/47363849/Christina+Aguilera+HQ+PNG.png";
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
// 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
NSDictionary *obj = [parser objectWithString:json_string];
//
NSString *status = [obj objectForKey:#"status"];
//
NSLog(#"status: %#", status);
This works when I pass the api key, secret and the IMAGE ON THE WEB as GET params, like:
http://api.face.com/faces/detect.json?api_key=4b4b4c6d54c37&api_secret= &urls= http://farm3.static.flickr.com/2566/3896283279_0209be7a67.jpg
Now, I want to upload a raw image data from my app...but this is not so well documented on the site:
http://developers.face.com/docs/api/faces-detect/
There it says:
Code:
Optional [no name] The raw image data for the photo (when instead of url, an image is uploaded)
This is the problem:
How do I pass the raw data as POST along with the apikey and secret?
I know it must be as POST, but how?
Raw data = NSData, so all you need to do is append the imageData to the URL, as done below.
NSString *url = [NSString stringWithFormat:#"http://api.face.com/faces/detect.json?api_key=myapi&api_secret=mysecret&code=%#", imageData];
EDITED CODE
I had done in this way:
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.google.com/maps?q=restaurant&sll=23.00,72.00&radius=2000&output=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:NSASCIIStringEncoding];
[json_string stringByReplacingOccurrencesOfString:#"while(1);" withString:#""];
NSDictionary *json_dict = [json_string JSONValue];
NSLog(#"%#",json_dict);
But then also I'm getting null in json_dict
I want to parse the data which I get from Google Webservice.
http://www.google.com/maps?q=restaurant&sll=23.00,72.00&radius=2000&output=json
I have used the below code:
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
// Prepare URL request for Getting the Restaurent at particular coordinate.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.google.com/maps?q=restaurant&sll=23.00,72.00&radius=2000&output=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];
But I am not getting the response. If I use some other API like: http://twitter.com/statuses/public_timeline.json, it will parse properly, but this does not work for Google APIs
I had checked the response string in JSON version. The response which we get is forming a proper tree. It is not showing any error but the array in response which I get is null.
EDIT:
I was looking into and found out that it is not a proper response as you get a file with JSON extension and not a JSON response as is the case with twitter api you are referring. So my advice refer google places api and find a JSON response for a list of restaurants and then try again.
In order to hit there api key you need authenticate with your own api key which you get using this.
once you get your api key you can hit the api like this..
https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AddYourOwnKeyHere
this in return will give you a JSON response which you can parse easily (this returns a dictionary) and voila you are done(this api is limited to 100 hits per day only.)... hoping this helps.
So your code will look like this and will work I have checked it...
/// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=5000&types=food&sensor=false&key=yourOwnAPIKey"]];
// 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];
NSLog(#"statuses:%#", statuses);
use this
NSDictionary *json_dict = [responseString JSONValue];
NSLog(#"%#",json_dict);
then you can fetch any value using its key
The response string from http://www.google.com/maps?q=restaurant&sll=23.00,72.00&radius=2000&output=json is started with while(1);, it is not a valid JSON, remove it should work.
you can use google places api by replacing url to this
https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=2000&types=restaurant&name=harbour&sensor=false&key=AddYourOwnKeyHere
Generate your key from Google "https://code.google.com/apis/console/?pli=1#project:305239127220"
Instead of creating a URLRequest you can directly download the contents from the URL into your jsonString like this
NSString * jsonString = [[NSString alloc] initWithContentsOfURL:#"http://www.google.com/maps?q=restaurant&sll=23.00,72.00&radius=2000&output=json" encoding:NSUTF8StringEncoding error:nil];
And convert this jsonString into NSDictionary using JSONParser.
Hope this will solve your issue.....
Try This One
Use SBJson Instead of jsonValue method.
1)import the "SBJSON.h"in .h ViewController.
NSString *jsonString;
//jsonString this is The Coming JSON Response.
SBJSON *parser = [[[SBJSON alloc] init] autorelease];
NSDictionary *jsonResponse = (NSDictionary*)[parser objectWithString:jsonString error:nil];
NSDictionary *responseData = [jsonResponse objectForKey:#"response"]; objectForKey:#"venues"] ;
//Further parsed the Data According to the Keys.
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.
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.