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

六月ゝ 毕业季﹏ 提交于 2019-12-22 09:31:10

问题


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?


回答1:


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:

http://validator.w3.org/




回答2:


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];



回答3:


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)
}



回答4:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!