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

夙愿已清 提交于 2019-12-05 17:33:40
occulus

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/

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

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