GJain
GJain

Reputation: 5093

iOS - error parsing JSON created using UTF8Encoding and sent as C string

First I do:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];

Then I do

  NSString *stringInJSONFormat = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

which gives me following output. I validate using http://jsonlint.com/

__NSCFString *  @"{\n  \"key1\" : \"value1\",\n  \"key2\" : \"value2\",\n  \"key3\" : \"value3\",\n  \"key4\" : \"value4\"\n}"  0x00007f7fe2cebfb0

Now to send the data across, I need to do (using a third party lib):

[myNSString UTF8String] and send

Now the string I get back on the receiving side is

__NSCFString *  @"{\\n  \"key1\" : \"value1\"\\,\\n  \"key2\" : \"value2\"\\,\\n  \"key3\" : \"value3\"\\,\\n  \"key4\" : \"value4\"\\n}"   0x00007fb0858e7190

And I can not de-serialize this string into valid JSON.

I do

[NSJSONSerialization JSONObjectWithData:[myNSString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error]

I suspect that the third-party lib is doing its own data escaping which is leading to this issue. But I am not sure.

Would you be able to point me to issue and a possible solution?

I get error

errorDesc __NSCFString * @"Error Domain=NSCocoaErrorDomain Code=3840 \"Invalid escape sequence around character 1.\" UserInfo={NSDebugDescription=Invalid escape sequence around character 1.}" 0x00007fff5293deb0

Upvotes: 1

Views: 610

Answers (1)

Farcaller
Farcaller

Reputation: 3070

It looks like your lib converts \n to \\n and , to \,, breaking the parser. I'd suggest you to try doing

str = [[str stringByReplacingOccurrencesOfString:@"\\n"
                                      withString:@"\n"]
       stringByReplacingOccurrencesOfString:@"\\,"
                                 withString:@","];

to see if it will help.

That's a pretty strange problem, but it addresses your immediate input example. You might want to dig further into the third-party lib to see if it's the onlt data corruption.

Upvotes: 1

Related Questions