NSJSONSerialization Returns Error of NULL - ios

I have the following code :
NSData * jsonData = [NSData dataWithContentsOfURL:location];
NSString* newStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *data = [newStr dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
if (jsonError) {
NSLog(#"JSON Error %#", [jsonError localizedDescription]);
}
NSArray * jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
Which is parsing the following JSON String :
{"author":"Oli Riman","content":"The museum shows us a view of pre-WWI society that includes doubts, fears, political protests etc. through newspaper cartoons of the time. Really interesting for adults who enjoy history. I wouldn't suggest this for kids who haven't studied WWI history or who don't read easily.","rating":"5","placeId":"40","date":"29-June-2015","reviewId":"9905A52D-76B2-4D42-8CA8-9158225C0D07"}
However I am getting a strange error code of :
domain: (null) - code: 0
Can anyone advise on what is causing this ?

Just tested the code on my simulator. Its working. You need to check if you are getting data from server or not.
If you want to test the parsing thing, you can do one thing-
Just store the data in json file and save it in the app bundle lets say file is "data.json"
and call below method, you will get data for sure.
- (void)readJsonData {
NSString *path = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"json"];
NSURL *url = [NSURL fileURLWithPath:path];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: data
options: NSJSONReadingAllowFragments
error: &error];
NSLog(#"Parsed json data- %#", dict);
}

Related

Getting Web service response in string Format

I am using Afnetworking Framework in my project but I am getting the response in string format. I want to get the value of "Data" in the response below -
"{\"Result\":\"Success\",\"Data\":\"intro-1898-1449000428650.mp4\"}"
I have used the code below:
[Helper PostWebServiceRequest:kIntrovideo InputParameters:parameters competion:^(BOOL result, NSDictionary *response) {
if (result){
NSLog(#"response : %#",response);
NSString *data= [NSString stringWithFormat:#"%#",response ];
NSError *jsonError;
NSData *objectData = [data dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
since your response object seems to be an array and not (as stated) a dictionary, try the following:
NSString *jsonString = ((NSArray *)response).firstObject;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSString *data = jsonObject[#"Data"];
Not sure, but it seems that server can't pass object in Json, it's should pass link to place from where you can download this Data.

iOS - How to properly read JSON file with umlauts

I am having difficulties converting a JSON file into an NSDictionary without losing umlauts.
{
"België": "5",
"Haïti": "45"
}
This is a short version of the contents of a .json file in my supporting files in Xcode.
I need to convert them to an NSDictionary without losing those umlauts.
NSString *file =[[NSBundle mainBundle] pathForResource:#"countries_and_rates" ofType:#"json"];
NSString *cr = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:NULL];
After that, I give cr to this method:
+ (NSDictionary*)jsonFromData:(NSData*)data {
if([self isEmpty:data] || ![data isKindOfClass:[NSData class]])
return nil;
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(!str)
return nil;
NSError* error;
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if(error)
NSLog(#"************** Error: jsonFromData: %#/%#", error.localizedDescription, error);
if([json isKindOfClass:[NSDictionary class]])
return json;
else if([json isKindOfClass:[NSArray class]])
return [NSDictionary dictionaryWithObject:json forKey:#"results"];
return #{};
}
If someone could help me and tell me what I am doing wrong.
FYI: tried all kinds of encoding, such as NSISO and NSUTF
Don't mess around with encodings, let the framework figure it out for you:
NSData *data = [NSData dataWithContentsOfFile:filepath];
NSError *error = nil;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

Json to iOS Encoding Error

Problem: I can't parse data from a JSON file to a NSArray appropriately. UTF encoding is not working as expected.
My JSON looks something like:
[
{"Name":"Marcos","Address":"1234 Brasil Av. São Paulo - SP","Latitude":"-23.000","Longitude":"-46.70"},{"Name":"Mario","Address":"1000 Washignton Luiz Av. Itú SP","Latitude":"-20.0000","Longitude":"-46.000"}
]
My Objective-C code is:
NSError *error = nil;
NSURL *jsonUrl = [[NSURL alloc]initWithString:
#"http://marcosdegni.com.br/teste/webservice_teste.php"];
NSString *jsonString = [NSString stringWithContentsOfURL:jsonUrl
encoding:NSUTF8StringEncoding error:&error];
NSLog(#"jsonString: %# , Error:%#:" ,jsonString, error); //(1)
if (!error) {
NSError *error2 = nil;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray * jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error2];
NSLog(#"\n\nArray: %#" \nError:$#, jsonArray, error2); //(2)
//(*1*) This log show the content's as they are expected: note the characters ã and ú on the address fields.
//(*2*) The logs from the array and the dictionary show this charters as it's UNIX codes:\U00e and \U00fa respectively.
You can give this a try. The id json you get will be a NSArray, you can use it from there.
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray * array = json;
for (NSDictionary *dict in array) {
NSString *string = [dict objectForKey:#"Address"];
NSLog(#"%#",string);
}
From here, and I get the right result if I obtain the value of the key and log it, instead of logging the NSArray directly.

How to get the values from json service [duplicate]

This question already has an answer here:
Parsing JSON response .
(1 answer)
Closed 8 years ago.
Hai I need to get the id & status from the service for login my code is below. please guide me to get the values.. Thanks in advance..
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.xxx/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSData *data=[NSData dataWithContentsOfURL:url];
1st Do the jSon parsing and then get the particular value from the
key .
Before getting any value , we have to understand the tree of jSon.
Here "posts" is an NSArray ,within that one DIctionary "post" is
there ,which again contains another dictionary.
Below is the complete code.
(void)viewDidLoad
{
[super viewDidLoad];
 NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link =
[NSString stringWithFormat:#"http://www.some.com/webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
}); }
Then call that selector fetchedData
(void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
 
if(!error){
NSArray* postArray = [json objectForKey:#“posts”]; //This is an array
if (postArray.count>0) {
NSDictionary *dict = [[postArray objectAtIndex:0] objectForKey:#"post" ];
NSString *id_ = [dict objectForKey:#"id"];
NSString *status_ = [dict objectForKey:#"status"];
}
}
}
Can you post your json string. You can use NSJSONSERIALISATION to convert data (json string ) into NSDictionary. Then use the keys to extract the values. I'm replying through mobile so I can't write the actual code.
Use Below code to parse Json in IOS
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.some.com/_webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSMutableURLRequest *req1 = [NSMutableURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//getting the data
NSData *newData = [NSURLConnection sendSynchronousRequest:req1 returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
NSLog(#"basavaraj \n\n\n %# \n\n\n",responseString);
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
NSString *id=[res objectForKey:#"ID"];
NSString *status=[res objectForKey:#"Status"];
and if u need extra info please go through below link it may help you
Click here for more details

Unable to read/parse a local json file

I am trying to parse a json file but I am unable to read/parse the data from the file. I prepared the The json data file by copying the contents from a web service call. I copied the contents and saved it in the projects directory. The path to the file is correct.
NSError *error;
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"js"];
NSLog(#"Path: %#", filePath);
// NSInputStream *fileInputStream = [[NSInputStream alloc] initWithFileAtPath:filePath];
// [fileInputStream open];
// NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithStream:fileInputStream options:0 error:&error];
// NSLog(#"Stream: %#", jsonData);
NSData *fileContents = [[NSData alloc] initWithContentsOfFile:filePath];
NSLog(#"Data: %#", fileContents);
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:fileContents options:kNilOptions error:&error];
NSLog(#"Dictionary: %#", jsonData);
The "fileContents" prints like "20202020 20202020 20202063 6c756249 64203d20" (may be it is hexadecimal value). Why am I getting the data like this? When I parse same date by calling the web service, it works fine.
I have left some commented code here to let you know that I have tried that portion as well.
Any help is much appreciated!!

Resources