Ata01
Ata01

Reputation: 303

How to parse JSON data from textual file in Objective-C

I know, JSON parsing questions are asked over and over again, but still I can't find any answer to this one.
I've been trying to read and parse a textual JSON file using NSJSONSerialization to no avail.
I've tried using the same JSON data from a NSString and it did work.
Here's the code:

NSError      *error;

NSString     *jsonString1 = [NSString stringWithContentsOfFile:jsonFilePath
                                                      encoding:NSUTF8StringEncoding
                                                         error:&error];
NSData       *jsonData1   = [jsonString1 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject1 = [NSJSONSerialization JSONObjectWithData:jsonData1
                                                            options:0
                                                              error:&error];

NSString     *jsonString2 = @"{\"key\":\"value\"}";
NSData       *jsonData2   = [jsonString2 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject2 = [NSJSONSerialization JSONObjectWithData:jsonData2
                                                            options:0
                                                              error:&error];

- The text file contains one line: {"key":"value"}
- jsonString1 = @"{"key":"value"}"
- jsonString2 = @"{\"key\":\"value\"}"
- jsonData1 is 23 bytes in size
- jsonData2 is 15 bytes in size
- jsonObject1 is nil and I get error code 3840
- jsonObject2 is a valid dictionary

Seems like the problem is with reading the file, since the NSStrings and NSDatas differ, but what am I doing wrong here and how can I fix it?

Upvotes: 1

Views: 700

Answers (2)

cbiggin
cbiggin

Reputation: 2142

I always do a check on the return value when doing anything with NSUTF8StringEncoding and if nil, then try NSASCIIStringEncoding:

NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (jsonString == nil) {
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
}

return jsonString;

Upvotes: 0

Cristik
Cristik

Reputation: 32789

Most likely you file contains some unprintable characters (e.g. \0) that trigger the failure. Printing the error message will tell you at what position the first invalid characters occurs.

For example, try printing "{\"key\":\u{0000}\"value\"}" and you'll seem to get a valid JSON, however decoding it fails.

Upvotes: 1

Related Questions