iOS JSON Parse Return null - ios

I have searched online for solution toward this problem, but the result that is always returned to me is null.
This is the following string that I received from a web. Everything seems to work fine. However, when I were to convert this string into an array then the result returned is null.
The code:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[self.responseData length]);
// String
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", responseString);
NSDictionary *resultsDictionary = [responseString objectFromJSONString];
NSLog(#"%#", resultsDictionary); // Returns null
}
The result:
[{"cid":"382595836","name":"\u514d\u7a0e\u5e97\u4e13\u5356\u54c1"},{"cid":"382595837","name":"\u9650\u91cf\u7248\u9999\u6c34"},{"cid":"380837083","name":"\u5973\u58eb\u7cbe\u88c5"},{"cid":"380837082","name":"\u7537\u58eb\u7cbe\u88c5"},{"cid":"61540749","name":"\u7b80\u88c5\u5973\u7528\u9999\u6c34"},{"cid":"24213689","name":"\u7b80\u88c5\u7537\u7528\u9999\u6c34"},{"cid":"25541561","name":"Q\u9999\u5973\u58eb"},{"cid":"25541841","name":"Q\u9999\u7537\u58eb"}]
May anyone provide me a way to think through this.
Thanks.

try this
NSMutableData *responseData; // use in .h class
use this function in use in .m class
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"connection did receive data");
[responseData appendData:data];
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(#"%#",responseString);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data", [responseData length]);
}

Use below code. The code will work on ios 5.0 and later.
NSArray* list = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions
error:&error];
I did this. It's working fine for me. Can you try below one logic.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"demo" ofType:#"json"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSError *error;
id json = [NSJSONSerialization JSONObjectWithData:myData options:kNilOptions error:&error];
NSArray *list = (NSArray *)json;

The objectFromJSONString will return nil if the string you're passing in isn't valid JSON.
I checked this
[{"cid":"382595836","name":"\u514d\u7a0e\u5e97\u4e13\u5356\u54c1"},{"cid":"382595837","name":"\u9650\u91cf\u7248\u9999\u6c34"},{"cid":"380837083","name":"\u5973\u58eb\u7cbe\u88c5"},{"cid":"380837082","name":"\u7537\u58eb\u7cbe\u88c5"},{"cid":"61540749","name":"\u7b80\u88c5\u5973\u7528\u9999\u6c34"},{"cid":"24213689","name":"\u7b80\u88c5\u7537\u7528\u9999\u6c34"},{"cid":"25541561","name":"Q\u9999\u5973\u58eb"},{"cid":"25541841","name":"Q\u9999\u7537\u58eb"}] 2012-11-30 14:29:52.779 com.JSON.Product[1979:c07]
in JSONLint it shows it is an invalid JSON.

Related

How to get value from json in ios application

i am getting response from the server in below method:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{
NSString * result;
NSMutableData * _responseData = [[NSMutableData alloc]init];
[_responseData appendData:data];
NSDictionary *dataAsString=(NSDictionary*)[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data in register reponse : %#",dataAsString);
I get this json value on logs:
dataAsString : {"status":"error","message":"MySQL Error: 1062 : Duplicate entry 'raushan#gmail.com' for key 'loginEmail'"}
Now I want to get a particular value from the string ,e.g. for key "status":
like the method below:
Nsstring * result=[dataAsString objectForKey:#"status"];
NSLog(#"result : %#",result);
but I dodn't get the result and my application crashes. I don't know what is wrong with that. I had tried a lots of way but not succeeded.
Please help me out. How can I retrieve value from dataAsString.
Thank you for your precious time.
NSJSONSerialization *json;
NSDictionary *dataJson;
NSError *error;
json=[NSJSONSerialization JSONObjectWithData:_responseData
options:NSJSONReadingMutableLeaves
error:&error];
dataJson=[[NSDictionary alloc]init];
dataJson=(NSDictionary *)json;
NSString * result=[dataJson valueForKey:#"status"];
if you are having more trouble, refer this link and this.
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:receiveddata options:0 error:&localError];
NSDictionary *result = [dataAsString objectForKey:#"result"];
NSString *statusString = [result objectForKey:#"status"];

Dealing with Unicode characters in NSArray after parsing a JSON feed

I've googled this to death and can't find the correct answer. Maybe I'm not phrasing the question correctly. I have a web service that provides a JSON feed. I log in and authenticate my username and password then parse some of the JSON feed and insert it into an NSArray as per below.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.urlData = [[NSMutableData alloc] init];
NSLog(#"DID RECEIVE RESPONSE");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
//NSLog(#"THE RAW DATA IS %#", data);
[self.urlData appendData:data];
//NSData
NSString *strRes = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(#"LOGGING THE DATA STRING %#", strRes);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *jsonParsingError = nil;
self.parsedJSONFeed = [NSJSONSerialization JSONObjectWithData:self.urlData options:0 error:&jsonParsingError];
self.titleList = [_parsedJSONFeed valueForKeyPath:#"response.page_items.title"];
self.dateList = [_parsedJSONFeed valueForKeyPath:#"response.page_items.date"];
//NSLog(#"RESPONSE: %#",[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]);
if (jsonParsingError) {
NSLog(#"JSON ERROR: %#", [jsonParsingError localizedDescription]);
} else {
//NSLog(#"PARSED OBJECT %#", parsedObject);
//NSLog(#"OBJECT: %#", [object class]);
}
[self.tableView reloadData];
}
So now "self.titleList" is an NSArray that contains text but the unicode characters have also passed through from the JSON feed. Is there a way to prevent this happening, or convert those unicode characters before/after parsing the JSON feed? Thanks in advance.
So in case anybody lands on this page with the same problem. In fact, they were HTML encoded unicode entities that were causing the problem.
Import this: https://github.com/Koolistov/NSString-HTML category into your project and send your NSString's to the relevant method. All working fine here now.

using json parser how to display php webservices data in UIview

i have a PHP webservices. My requirement is using PHP web services to display json data in UIView one by one.
The Json data is :
"id\":\"6\",\"title\":null,\"description\":null,\"year\":\"2012\",\"date\":null}","{\"id\":\"4\",\"title\":\"
correct in the year 2013\",\"description\":\"<\/font> Financial
system in America for this year is not indicated progress this year
too. More problems will creep up. \r\n<\/font> Aggressive stage
of Telangaana agitation- formation of seperate Telangaana state-
bifurcation of state - sure indications are \r\n\r\npredicted.
\r\n*<\/font> The Gujarath CM - Sri Narendra Modi - Bright future
is indicated. \r\n*<\/font> Still danger is indicated for
Indoneshia and Sumitra Islands.
i want to display these data in UIView.Before display each line of data displaying * symbol.How to retrieve and how to display in UIViewcontroller.Help me any body.Thanks in advance.
I am writing like this.but i got exception.
-(void)loadData
{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults valueForKey:#"id"];
[defaults valueForKey:#"title"];
[defaults valueForKey:#"description"];
[defaults synchronize];
NSURL *url=[NSURL URLWithString:#"http://www.predictions.php"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
urlConnection=[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData=[[NSMutableData alloc]init];
[responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(connection==urlConnection)
{
strResponse=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",strResponse);
NSError *error;
jsonDict=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",jsonDict);
NSArray *arrResults=[jsonDict valueForKey:#"id"];
NSLog(#"%#",arrResults);
arrString=[NSMutableArray array];
for(NSDictionary *dictRes in arrResults)
{
constants *con=[[constants alloc]init];
con.titl=[dictRes valueForKey:#"title"];
// con.desc=[dictRes valueForKey:#"description"];
[arrString addObject:con];
}
[View1 reloadData];
}
}
You can use NSJSONSerialization class for parsing JSON objects.
Hope this helps.
You should use this framework: https://github.com/stig/json-framework and SBJsonParser class to parse the JSON script. The below code will help you parse json response:
SBJSON *parser = [[SBJSON alloc] init] ;
NSDictionary *dic = (NSDictionary *)[parser objectWithString:respString error:nil];
This code will convert your response string in the respString variable into an NSDictionary, and now you can extract each object by calling:
NSString* response = [dic objectForKey:#"response"];

How can we retrieve data in iOS by JSON parsing?

I am calling this method in my Application.
[flickrRequest callAPIMethodWithPOST:#"flickr.photosets.create" arguments:[NSDictionary dictionaryWithObjectsAndKeys:FLICKR_AUTH_TOKEN,#"api_key",albumNAME,#"title",#"13978764555",#"primary_photo_id",#"Uploaded from my iPhone/iPod Touch", #"description", nil]];
JSON Response:
{ "photoset": { "id": "72157644227295321", "url": "https:\/\/www.flickr.com\/photos\/122586274#N04\/sets\/72157644227295321\/" }, "stat": "ok" }
I am getting this response on my log cat, now the problem is that i want to retrieve this "id" in my application,but i am unable to do this. Please help me in the way in which i can retrieve this id?
After the data returned from server, you can convert it to NSDictionary
NSError *error;
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:dataFromServer options:NSJSONReadingMutableContainers error:&error];`
Now since id is in the 2nd layer, so you can do
NSString *id = [[response objectForKey:#"photoset"] objectForKey:#"id"];
Make sure that you perform the nsjsonserialization in the
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
method.
You need to create a instance variable in the #interface like this:
#interface TheClass: NSObject<NSURLConnectionDelegate>
{
NSMutableData *_responseData;
}
And then fetch the data this way:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *error;
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:_responseData options:NSJSONReadingMutableContainers error:&error];
}
All data hasn't been receieved until the connectionDidfinishLoading method is executed.

objectFromJSONString in JSONKit.h returns null in iOS

Please do the following to reproduce the problem
NSString *url = #"http://qdreams.com/laura/index.php?request=EventWeekListings&year=2012&month=10&day=22";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#" , json);
NSDictionary *deserializedData = [json objectFromJSONString];
deserializedData would contain nil. Expected behavior is to return proper dictionary.
Is that because total number of JSON dictionary elements exceed a certain threshold?
I would appreciate any help in this matter.
Why not just use the NSJSONSerialization method JSONObjectWithData:options:error: it worked fine for me.
NSString *url = #"http://qdreams.com/laura/index.php?request=EventWeekListings&year=2012&month=10&day=22";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"%#",arr);
After Edit: I ran the code again this morning, and like you I got null. The problem with dataWithContentsOfURL. is that you have no control and no way to know what happened if something went wrong. So, I retested with the code below:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[self loadData];
}
-(void) loadData {
NSLog(#"loadData...");
self.receivedData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:#"http://qdreams.com/laura/index.php?request=EventWeekListings&year=2012&month=10&day=22"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10.0];
[NSURLConnection connectionWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"didReceiveResponse...");
[self.receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"didReceiveData...");
NSLog(#"Succeeded! Received %ld bytes of data",[data length]);
[self.receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"didFailWithError...");
NSLog(#"Connection failed! Error - %# %#",[error localizedDescription],[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
//lblError.text = [NSString stringWithFormat:#"Connection failed! Error - %#",[error localizedDescription]];
self.receivedData = nil;
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading...");
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:self.receivedData options:kNilOptions error:&error];
if (error) {
NSLog(#"%#",error.localizedDescription);
NSLog(#"%#",[[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]);
}else{
NSLog(#"Finished...Download/Parsing successful");
if ([result isKindOfClass:[NSArray class]])
NSLog(#"%#",result);
}
}
There was an error, and the log of error.localizesDescription was: "The data couldn’t be read because it has been corrupted". So, it appears that there is something wrong with what's coming back from the server which prevents the JSON parser from working correctly. I also printed out the string along with the error message. Maybe you can look at it carefully and try to figure out what's wrong with the data.
looking at your json you start with the array value (using square brackets) without a name. try reformatting you response with something like this:
{"results":[...the rest of your response..]}

Resources