iOS – NSJSONSerialization:无法将数据转换为字符串周围的字符串

我在解析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.} 

有任何建议如何解决这个问题?

添加正如错误报告中所述,解析器无法遍历位置73053处的字符,即我的JSON响应中的“ø”。 据我所知,像Ø,Å,Æ等字符应该不是json解析器的问题?

检查您正在解析的数据是否实际上是有效的JSON(而不仅仅是’几乎’JSON)。 当您有不同的数据格式无法解析为JSON时,就会发生该错误。 参见例如:

在cocoa错误3840中的iOS 5 JSON解析结果

你的JSON中也有一个顶级容器吗? 数组或字典。 例:

 { "response" : "Success" } 

更新

JSON的默认编码是UTF-8。 对于UTF-8,特殊/异国情调字符不是问题,但请确保您的服务器正确地将其内容正确编码为UTF-8。 另外,你有没有告诉你的JSON解释器使用不同的编码?

如果您的JSON来自Web服务,请将URL放入此页面以查看有关编码的内容:

http://validator.w3.org/

是的,我遇到了与编码问题相同的问题并得到了上述错误。 我从服务器获得NSData作为encoding:NSISOLatin1StringEncoding 。 所以我必须在使用NSJSONSerialization解析之前将其转换为UTF8。

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