iOS - NSJSONSerialization: Unable to convert data to string around character

Oleg picture Oleg · Jan 14, 2013 · Viewed 14.1k times · Source

I'm getting this error while parsing JSON:

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unable to convert data to string around character 73053.) UserInfo=0x1d5d8250 {NSDebugDescription=Unable to convert data to string around character 73053.}

Any suggestions how to fix this?

ADDED As it says in error report, the parser can't go through the character at position 73053, which is "ø" in my JSON response. As far as I know characters like Ø,Å,Æ etc. shouldn't be a problem for json parsers?

Answer

karim picture karim · Feb 11, 2016

Yes, I have the same problem with encoding issue and got the above error. I got the NSData from server as encoding:NSISOLatin1StringEncoding. So I had to convert it to UTF8 before parsing it using NSJSONSerialization.

NSError *e = nil;
NSString *iso = [[NSString alloc] initWithData:d1 encoding:NSISOLatin1StringEncoding];
NSData *dutf8 = [iso dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:dutf8 options:NSJSONReadingMutableContainers error:&e];