Error Store NSdata to NsDictonary - ios

plz help me to parse JSON data. we get response in NSMutable Data. but we cn't take out data in Dictionary. my jsonDictionary get nil.
this is my Url . i have check on JSON Validator.They show Valid Json output. help....
http://mobileapp.merucabs.com/NearByCab_ETA/GetNearByCabs.svc/rest/nearby?Lat=23.0768222&Lng=72.645732&SuggestedRadiusMeters=5000&CabMaxCount=10
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
// NSString *responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
//NSLog(#"Response String is %#",responseString);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
jsonDictionary=[NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];
jsonArr=[jsonDictionary objectForKey:#"results"];
// NSLog(#"JSONDictionary is %#",jsonDictionary);
[_categoryListTableView reloadData];
}

I got the output from your URL and I created the New project and Run , the project link is attach here

remove the line from the result <stringxmlns="http://schemas.microsoft.com/2003/10/Serialization/">
and try again
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
id jsonDictionary=[NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:nil];
NSLog(#"JSONDictionary is %#", jsonDictionary);
}

Your json service is returning invalid json. If you inspect the source code of that url you will find
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
on the header of the file. Make sure the json validity with some validation tools like jsonlint.com

Related

i Can't convert NSData to NSMutableArray

I want to try to convert NSData to NSDictionary or NSArray but some how i can't do that but whenever try to convert into NSString it will converted and gating data so any one can know what is mistake ,help me below is code for convert
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
Below code for convert into NSString
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
But Problem is that When get this type of data it will converted on array
Response:
[["superwoman",0],["sugar",0],["sultan trailer",0],["summer",0],["superman",0],["sunday candy",0],["sublime",0],["summer sixteen",0],["superfruit",0],["sultan songs",0]]
but Whenever gat this type of response it will not converted on array formated because of ,[3 on response
Response:
[["ssundee",0],["selena gomez",0],["sia",0],["sorry beyonce",0],["smosh",0],["sweatshirt jacob
sartorius",0],["skydoesminecraft",0],["secret life of pets
trailer",0,[3]]
try this one
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:&error];
1)You need to take the response in id type variable & check the class of response like below.
2)You also need to check if JSON convertion is successful
NSError * error;
id result = [NSJSONSerialization JSONObjectWithData:data
options:0 error:&error];
if (!error) {
if([id isKindOfClass:[NSDictionary class]]){
//Response is Dictonary
} else if ([id isKindOfClass:[NSArray class]]){
//Response is Array
} else {
//any other format
}
} else {
//Handle error
}

The data couldn’t be read because it isn’t in the correct format

Ok, I am now starting with iOS development and currently playing with NSData using Obj-C. Recently I'm using the URLSession:dataTask:didReceiveData method to get NSData using HTTP POST request. The server will be responding a JSON object containing a JSON array.
Something interesting is that when the response data is too large the NSLog part will print out: "The data couldn't be read because it isn't in the correct format". Below is the function:
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
NSError *error;
// get data from NSData into NSDict
NSDictionary *searchData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSArray *test = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSMutableDictionary *mdict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"what: %#", mdict);
NSLog(#"received data length: %#", [NSByteCountFormatter stringFromByteCount:data.length countStyle:NSByteCountFormatterCountStyleFile]);
if (error) {
NSLog(#"json error: %#", [error localizedDescription]);
}
}
Just wondering if anyone knows the potential reason causing this problem ??
[Update]
Well, an alternative to solve this problem might be using NSString for data storage. But would have to parse it by myself. I would prefer using NSDictionary though.
Beginner problem: didReceiveData is called when some of the data has arrived, before the data is complete. Read the documentation of didReceiveData, which explains what you need to do. You are trying to parse incomplete data. That won't work.
And when you are handling JSON data, you should never involve any NSString objects, except possibly to log data.
In my case i was hitting POST Method instead of GET. Solved my problem.
At first point you should check if the response received from the API is a valid JSON, can be check by online validators like jsonlint.com. If this is a vaid json, then you are good to go.
Further more you should evaluate the error object on every step when you get it to see which parsing of data cause this problem like:
NSError *error;
// get data from NSData into NSDict
NSDictionary *searchData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
if (error) {
NSLog(#"json error: %#", [error localizedDescription]);
}
NSArray *test = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSMutableDictionary *mdict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"what: %#", mdict);
NSLog(#"received data length: %#", [NSByteCountFormatter stringFromByteCount:data.length countStyle:NSByteCountFormatterCountStyleFile]);
if (error) {
NSLog(#"json error: %#", [error localizedDescription]);
}
Also, as you said that:
The server will be responding a JSON object containing a JSON array.
Are you sure it is returning NS(Mutable)Dictionary ?? Try printing it like this:
id response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
if (error) {
NSLog(#"json error: %#", [error localizedDescription]);
}
else
{
NSLog(#"json data : %#", response);
}
if the data is kind of josn ,you can
NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
or
[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding])
,so that you will be get nsdictionary or nsstring data, if you cannot parse it by yourself ,you can user jsonModel tranlte to model .
It may be a problem with your json data I have experienced the same. You have to serialize your json data like this below written code
NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
If you are populating json data from data base u have to use Nsarray.
Hope this will help you .

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.

iOS JSON Parse Return null

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.

Resources