Unable to read/parse a local json file - ios

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!!

Related

JSON Serialization returns null from local file

I'm writing JSON to disk, and that works great. But when I try to read it back, it is nil.
Specifically, this line is nil: NSMutableDictionary *jsonDictFromDocuments = [NSJSONSerialization JSONObjectWithData:[jsonString2 dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];. (I tried NSDictionary *jsonDict2 = [NSJSONSerialization JSONObjectWithData:jsonData2 options:kNilOptions error:&jsonError]; too, but still got nil.)
Every line up until that point logs the correct information from what I can tell.
// Read JSON back from disk
NSString *fileName2 = #"/myJSONFull.json";
NSLog(#"FN: %#", fileName2);
NSURL *documentsFolderURL2 = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSLog(#"dFURL2: %#", documentsFolderURL2);
NSString *filePath2 = [documentsFolderURL2.path stringByAppendingString:fileName2];
NSLog(#"FP2: %#", filePath2);
NSString *jsonString2 = [[NSString alloc] initWithContentsOfFile:filePath2 encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"JSONs2: %#", jsonString2);
NSError *jsonError;
NSData *jsonData2 = [jsonString2 dataUsingEncoding:NSASCIIStringEncoding];
NSDictionary *jsonDict2 = [NSJSONSerialization JSONObjectWithData:jsonData2 options:kNilOptions error:&jsonError];
NSLog(#"JDFD2: %#", jsonDict2);
NSMutableDictionary *jsonDictFromDocuments = [NSJSONSerialization JSONObjectWithData:[jsonString2 dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
NSLog(#"JDFD: %#", jsonDictFromDocuments);
Any ideas?
EDIT:
This is what I have now, but it is still nil
// Read JSON back from disk
NSString *fileName2 = #"/myJSONFull.json";
NSURL *documentsFolderURL2 = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSString *filePath2 = [documentsFolderURL2.path stringByAppendingString:fileName2];
NSString *jsonString2 = [[NSString alloc] initWithContentsOfFile:filePath2 encoding:NSUTF8StringEncoding error:NULL];
NSError *jsonError;
NSData *data = [NSData dataWithContentsOfFile:filePath2];
NSMutableDictionary *jsonDictFromDocuments = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
Please try this, it uses the URL related API and logs a possible error in the deserialization.
NSString *fileName2 = #"myJSONFull.json";
NSLog(#"FN: %#", fileName2);
NSURL *documentsFolderURL2 = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSLog(#"dFURL2: %#", documentsFolderURL2);
NSURL *fileURL = [documentsFolderURL2 URLByAppendingPathComponent:fileName2];
NSLog(#"FP2: %#", fileURL);
NSData *jsonData = [NSData dataWithContentsOfURL:fileURL];
NSError *jsonError;
NSDictionary *jsonDict2 = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];
NSLog(#"JDFD2: %# - error: %#", jsonDict2, jsonError);
Edit:
Since your JSON is PLIST in reality –
the error message JSON text did not start... means This is no JSON –
use the appropriate serialization class:
...
NSLog(#"FP2: %#", fileURL);
NSData *plistData = [NSData dataWithContentsOfURL:fileURL];
NSError *plistError;
NSArray *plistArray = (NSArray *)[NSPropertyListSerialization propertyListWithData:plistData
options:NSPropertyListImmutable
format:nil
error:&plistError];
NSLog(#"JDFD2: %# - error: %#", plistArray, jsonError);

NSJSONSerialization Returns Error of NULL

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);
}

arrayWithContentsOfFile and arrayWithContentsOfURL nil

When I call [NSArray arrayWithContentsOfFile:], I get nil.
NSURL *fileURL = [NSURL URLWithString:className relativeToURL:[self JSONDataRecordsDirectory]];
return [NSArray arrayWithContentsOfFile:[NSString stringWithFormat:#"%#", [fileURL path]]];
Alternatively, I also get nil when I call:
[NSArray arrayWithContentsOfURL:]
The results of all my files are in JSON here:
https://gist.github.com/neverbendeasy/03d047a6789b0ae14e1f
When I check the fileURLs, the data is there.
What am I missing?
You can't load a JSON file using NSArray arrayWith.... That method can only load a plist file with an array as the root.
If your file is a JSON file you should use:
NSData *jsonData = [NSData dataWithContentsOfURL:fileURL];
NSError *error = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if (jsonArray) {
// do something with jsonArray
} else {
NSLog(#"Couldn't load JSON from %#: %#", fileURL, error);
}
This assumes the top level of the JSON file is an array.
Use NSURL's
+ (id)fileURLWithPath:(NSString *)path
or
+ (id)fileURLWithPath:(NSString *)path isDirectory:(BOOL)isDir
instead of
+ (id)URLWithString:(NSString *)URLString
when working with the local filesystem.

IOS Encoding ISO-8859-9

I need to get contents of an XML file which is hosted on web, and parse it.
I decided to use TouchXML for parsing process. However, I cannot get contents of the file since it is encoded with ISO-8859-9
XML File Url: http://rss.haberler.com/mobil/sondakika2.asp?kategori=manset
I have tried 2 different approachs.
1) Getting contents of url into NSString:
NSString *url = #"http://rss.haberler.com/mobil/sondakika2.asp?kategori=manset";
NSError *error = nil;
NSStringEncoding encoding;
NSString *xmlString = [[NSString alloc] initWithContentsOfURL: [NSURL URLWithString:url] usedEncoding:&encoding error:&error];
xmlString becomes null, and error description says:
The operation couldn’t be completed. (Cocoa error 261.)
Instead of usedEncoding, I also tried specifying encoding explicitly, from UTF-8 to NSISOLatin1StringEncoding and NSISOLatin2StringEncoding (unfortunately, I could not find NSISOLatin9StringEncoding).
2) I also tried to load xml into NSData.
NSError *error = nil;
NSData *XMLData = nil;
XMLData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:url] options:0 error:&error];
When I constructed XML Parser, specific characters are unknown and application terminates when I get string values.
CXMLDocument *doc = [[CXMLDocument alloc] initWithData:XMLData options:0 error:nil];
NSArray *nodes = [doc nodesForXPath:#"//item" error:nil];
for (CXMLElement *node in nodes) {
for(int counter = 0; counter < [xmlElement childCount]; counter++) {
CXMLNode * child = [xmlElement childAtIndex:counter];
NSString *childName = child.name;
NSString * childValue = [child stringValue];
}
}
Getting stringValue of child terminates application with SIGABRT.
How can I fix the problem?
From the TouchXML CXMLDocument.m file, this is what initWithData: looks like
- (id)initWithData:(NSData *)inData options:(NSUInteger)inOptions error:(NSError **)outError
{
return [self initWithData:inData encoding:NSUTF8StringEncoding options:inOptions error:outError];
}
What you could try doing is, in this file, replace NSUTF8StringEncoding with NSASCIIStringEncoding or whatever encoding it uses. That may fix it.

iOS - How to get more debugging information on nil return values

In my iOS 5.1 application, I'm trying to load a JSON text file into a NSDictionary.
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"stuff" ofType:#"json"];
NSDictionary *stuff = [NSDictionary dictionaryWithContentsOfFile:filepath];
The filepath is valid, the file exists, but stuff is nil, which means there was a problem decoding the file (according to the documentation).
(How) Can I get more debugging information on why [NSDictionary dictionaryWithContentsOfFile:] - or any kind of API call - returns nil?
Read the contents as NSData and then use +[NSPropertyListSerialization propertyListWithData:options:format:error:].
As you said: Your file contains a JSON string. First, you have to load the string and then you have to parse it using some JSON library.
E.g.:
NSError *error;
NSString *content = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:&error]; //error checking omitted
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *json = [parser objectWithString: content];

Resources