getting error during json parsing - iphone

I am getting error during json parsing. When I trying to send the parameters using browser then it send me the success message that record store successfully. But when I send form parameters through iphone then i get nothing and in array i get NULL value.This is the json parsing code.
NSString *string1 = [[NSString alloc]initWithFormat:#"http://195.78.76.34/bedspace/mobileapi.php?action=save_room_info&Area=%#&Address=%#&Living_room=%#&Amenties=%#&Type_of_cost=%#&cost_of_room=%#&Security_deposit=%#&STLC=%#&Days_available=%#&Bill_included=%#&Broadband_available=%#&Exc_Smoke=%#&Exc_gender=%#&Exc_pets=%#&Exc_age=%#&Exc_language=%#&Exc_nationality=%#&Exc_Sexorientition=%#&Exc_intrest=%#&Pre_smoke=%#&Pre_gender=%#&Pre_occupation=%#&Pre_pets=%#&Pre_min_age=%#&Pre_max_age=%#&Pre_nationaltiy=%#&Pre_Language=%#&Pre_Sexorientition=%#&Misc=%#&Title=%#&Description=%#&Your_name=%#&Your_email=%#&Email_alert=%#&No_of_rooms=%#&Country=%#&City=%#&State=%#&Size_of_property=%#&Type_of_property=%#&Occupets_property=%#&My_property_status=%#&Amenties_two=%#&Size_of_room=%#&Refrence_required=%#",area,address,livingRoomVal,amenties,typeOfCost,costOfRoom,securityDeposit,STLC,daysAvailable,billsIncluded,broadbandAvailable,eSmoke,eGender,ePets,eAge,eLanguage,eNationality,eSexOrientation,eInterest,pSmoke,pGender,pOccupation,pPets,pMinAge,pMaxAge,pNationality,pLanguage,pSexOrientation,misc,title,description,yourName,yourEmail,emailAlerts,noOfRooms,country,city,state,sizeOfProperty,typeOfProperty,occupentsOfProperty,myPropertyStatus,amentiesTwo,sizeOfRoom,refrenceRequired];
NSLog(#"string 1 value %#",string1);
NSURL *urlRequest = [NSURL URLWithString:string1];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:urlRequest];
NSData *dataResponce = [NSURLConnection sendSynchronousRequest:request returningResponse:Nil error:Nil];
NSError *jsonParsingError = nil;
NSArray *publicTimeline = [NSJSONSerialization JSONObjectWithData:dataResponce options:0 error:&jsonParsingError];
NSLog(#"get values %#",publicTimeline);
I don't know what the problem is. I also used SBJsonParser but i get nothing in array and after that I used NSJSONSerialization and same problem still happen i got nothing in NSData and in NSArray.

You cannot fill the URL with parameters and still expect it to be legal, so you need to URL Encode the URL before use:
NSURL *urlRequest = [NSURL URLWithString:[string1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Related

NSJSONSerialization does not return data, but its showing data in json viewer

NSJSONSerialization returns null when i try to implement a particular api from the server, but other api's from the server works fine , when i tried the api in web it returns data of json type , and i have checked it in json viewer also , and it worked fine , NSData also returns some data, can Anyone help me get through it ?
NSString *urlString = #"url";
NSURL *url = [NSURL URLWithString:urlString];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:url];
_dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if(error != nil){
NSLog(#"JSON Error: %#", error);
return;
}
I have tried the above written code.
---Edited-----
Since it was a issue from server side as server was sending an Invalid Character along with response, In json validator it was passing but not in a actual Program , Hence closing the question.
The Problem is of Escape Sequences in your URL and you are not escaping them. You have to escape those sequences properly.
NSString *urlString = #"url";
NSString *encodedString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodedString];
Take a Look at Documentation.
Check also the Escape Sequences.
Try this :
NSString *urlString = #"url";
NSURL *myUrl = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Make a NSURLConnection and request the JSON with NSURLRequest because I don't think the 'json' is an actual file that has content so you could use dataWithContentsOfURL:

Can't fetch data from NSURL

I am fetching result from google place search url, if I search for "Newyork", everything works fine. But if I give "New york", the result json is different and I can't take it in NSData.
This is the url I am using:
https://maps.googleapis.com/maps/api/place/textsearch/json?query=New york&sensor=true&key=MY_KEY
I am using below code to fetch the data:
NSURL *googleURL = [NSURL URLWithString:url]; //url is above url
NSURLResponse *response;
NSData *data;
NSError *error;
data = [NSURLConnection sendSynchronousRequest: [NSURLRequest
requestWithURL: googleURL] returningResponse: &response error: &error];
NSLog(#"data %#",data); // but I am getting null here
How to overcome this? Thanks in advance
Assuming that url is:
NSString *url = #"https://maps.googleapis.com/maps/api/place/textsearch/json?query=New york&sensor=true&key=MY_KEY";
Try using this:
NSURL *googleURL = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
This will format the string for URLs containing spaces. To confirm it is working, print it out to the console.
NSLog(#"URL with Percent Escapes: %#", [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
It should return something like this (I believe the percent escape for a space is %20).
URL with Percent Escapes: https://maps.googleapis.com/maps/api/place/textsearch/json?query=New%20york&sensor=true&key=MY_KEY

From iphone app to face.com api: upload raw image

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

Parsing JSON from Google API on iPhone

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.

How to decode UTF8 characters with JSON on iPhone?

I'm using ASIHTTP Request to get a NSString response that I give to a SBJSON parser.
The problem is that inside the NSString response I got some UTF8 encoded character(accent) that I need do decode to make the app works.
How can I decode UTF8 with JSON ?
I call the JSON message like this:
[jsonParser objectWithString:jsonString error:NULL];
Any help would be so appreciated.
Fabrizio
lol....
great !
but for more simplicity i will say.
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]
And in statuses array you have all the data you need.
I just realized I didn't have to decode, the response is correctly read.
Thanx for reading.
Fabrizio