【问题标题】:iOS - NSJSONSerialization: Unable to convert data to string around characteriOS - NSJSONSerialization:无法将数据转换为围绕字符的字符串
【发布时间】:2013-01-14 15:08:22
【问题描述】:

解析 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,看起来它是有效的
  • 您能发表您的回复吗?谷歌搜索该错误显示具有有效 JSON 的人的结果,但他们的响应格式不正确。前任。 stackoverflow.com/questions/9282771/…stackoverflow.com/questions/9282771/…
  • 也许你应该发布围绕问题字符的 JSON 的 sn-p。

标签: ios objective-c xcode cocoa-touch nsjsonserialization


【解决方案1】:

是的,我在编码问题上遇到了同样的问题,并得到了上述错误。我从服务器获取 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];

【讨论】:

  • 上帝保佑卡里姆先生!
  • 你好,如何能够看到正在发回的编码?在你的情况下,它是 NSISOlating1stringEncoding,我怎样才能弄清楚我的发回了什么?
【解决方案2】:

斯威夫特 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)
}

【讨论】:

  • 太好了,谢谢
【解决方案3】:

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

iOS 5 JSON Parsing Results in Cocoa Error 3840

您的 JSON 中也有顶级容器吗?数组或字典。示例:

{ "response" : "Success" }

更新

JSON 的默认编码是 UTF-8。特殊/奇异字符对于 UTF-8 来说不是问题,但请确保您的服务器返回正确编码为 UTF-8 的内容。另外,你有没有做任何事情告诉你的 JSON 解释器使用不同的编码?

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

http://validator.w3.org/

【讨论】:

  • 是的,需要确保发送的字符编码与解析器预期的相同。 DBCS 编码方案中的冲突很可能是这里的问题。
  • 稍微延迟接受您的答案 :-) 通过使用 UTF-8 对输出字符串进行编码解决了问题。
  • 对我有很大帮助!有时服务器端可能会用GBK编码回调我们,因此可能会导致这个问题。在我的情况下,我注意到数据编码是GBK,所以我手动将编码转换为NSUTF8。
【解决方案4】:

斯威夫特 5:

是的,我在解析 JSON 数据时遇到了同样的错误。

解决方案:您必须先将响应数据转换为字符串,然后在解码之前使用 UTF8 编码将该字符串转换为数据。

let utf8Data = String(decoding: responseData, as: UTF8.self).data(using: .utf8)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多