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?
Check that the data you're parsing is actually valid JSON (and not just 'nearly' JSON). That error is known to occur when you have a different data format that can't be parsed as JSON. See for example:
iOS 5 JSON Parsing Results in Cocoa Error 3840
Do you have a top-level container in your JSON too? An array or dictionary. Example:
{ "response" : "Success" }
Update
JSON's default encoding is UTF-8. Special/exotic characters aren't a problem for UTF-8, but please ensure that your server is returning its content properly encoded as UTF-8. Also, have you done anything to tell your JSON interpretter to use a different encoding?
If your JSON is coming from a web service, put the URL into this page to see what it has to see about the encoding:
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];
Switf 3
let responseStrInISOLatin = String(data: data, encoding: String.Encoding.isoLatin1)
guard let modifiedDataInUTF8Format = responseStrInISOLatin?.data(using: String.Encoding.utf8) else {
print("could not convert data to UTF-8 format")
return
}
do {
let responseJSONDict = try JSONSerialization.jsonObject(with: modifiedDataInUTF8Format)
} catch {
print(error)
}
Swift 5:
Yes, i got the same error while parsing JSON data.
Solution : You have to first convert response data into String and then convert that Sting to Data using UTF8 encoding before decoding.
let utf8Data = String(decoding: responseData, as: UTF8.self).data(using: .utf8)
来源:https://stackoverflow.com/questions/14321033/ios-nsjsonserialization-unable-to-convert-data-to-string-around-character