I'm having a hard time parsing the below JSON string on iOS 5.
{"States": [{"Name": "Arizona","Cities": [{"Name": "Phoenix"}]},{"Name": "California","Cities": [{"Name": "Orange County"},{"Name": "Riverside"},{"Name": "San Diego"},{"Name": "San Francisco"}]},{"Name": "Nevada","Cities": [{"Name": "Las Vegas"}]}]}
And here's my code:
- (void) parseJson {
NSError *jsonError = nil;
NSData *jsonData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Locations-JSON" ofType:@"rtf"]];
if (jsonData) {
NSDictionary *jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&jsonError];
if (jsonError) {
NSLog(@"JSON Error: %@", [jsonError localizedDescription]);
return;
}
NSLog(@"%@", jsonObjects);
}
}
I keep getting this error:
JSON Error: The operation couldn’t be completed. (Cocoa error 3840.)
I'd appreciate some help on this because I clearly and incapable of fixing this.
I was able to troubleshoot my JSON 3840 error by converting the
NSData
object to anNSString
:One thing that strikes me as incorrect is this:
Your data is an RTF file?? It should be a
txt
file (or any other sort of plain text file). RTF files usually contain text formatting data, like this:When I read that in as a data and try to parse it as JSON, I get the 3840 error you're seeing. That error's description says:
So what it looks like to me is that you don't actually have JSON. You have RTF data.
I had hit a similar problem. My JSON parser works intermittently when I download the JSON data from a server. Did you get your JSON data from this function?
The NSData returned from this function could be partial data. You need to appendData to an instance variable with type: NSMutableData. Then you process your JSON in another function as follows:
Reading this article for the details. It works for me
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
If you arrived here because of the JSON and not because of the RTF , please check out this answer : IOS JSON Deserialization failure - STIG/NSJSONSerializer