【问题标题】:Invalid JSON while parsing \n (quoted) string解析 \n(引用)字符串时 JSON 无效
【发布时间】:2019-05-31 03:44:12
【问题描述】:

我的 Codable 解析有问题...这是我的示例代码:

class Test: Codable {
      let resultCount: Int?
      let quote: String?
}

 var json =  """
{
    "resultCount" : 42,
    "quote" : "My real quote"
}
""".data(using: .utf8)!

 var decoder = JSONDecoder()
 let testDecoded = try! decoder.decode(Test.self, from: json)

这里一切都按预期工作,并创建了 Test 对象。

现在我的后端向我发送引号字符串,中间有一个引号......以这种形式(请注意\“real\”):

class Test: Codable {
      let resultCount: Int?
      let quote: String?
}

 var json =  """
{
    "resultCount" : 42,
    "quote" : "My \"real\" quote"
}
""".data(using: .utf8)!

 var decoder = JSONDecoder()
 let testDecoded = try! decoder.decode(Test.self, from: json)

在第二种情况下,解码器无法创建对象...这是我的错误消息:

dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "给定的数据不是有效的 JSON。", 基础错误:可选(错误域=NSCocoaErrorDomain 代码=3840 “字符 4 周围的对象中没有值的字符串键。” UserInfo={NSDebugDescription=对象周围的值没有字符串键 字符 4.})))

有没有办法解决这个问题?

【问题讨论】:

  • JSON 中的嵌入引号必须进行转义。在您的字符串文字中,这将是 "My \\"real\\" quote"
  • 您需要在字符串文字中使用\\ 来转义"。使用这样的字符串,您的代码就可以正常工作。您的后端是否发送了带有转义引号的真实 JSON?您应该将实际的 JSON 放在一个文件中,以绕过您需要在字符串文字中执行的双重转义,并使用它进行测试以模仿后端。

标签: json swift codable jsondecoder


【解决方案1】:

要在 JSON 中包含引号,字符串中的引号之前必须有实际的 \ 字符:

{
    "resultCount" : 42,
    "quote" : "My \"real\" quote"
}

要在 Swift 字符串文字中执行此操作,您需要转义 \。这导致 Swift 多行字符串文字中的 "My \\"real\\" quote"

let json = """
    {
        "resultCount" : 42,
        "quote" : "My \\"real\\" quote"
    }
    """.data(using: .utf8)!

let decoder = JSONDecoder()
let testDecoded = try! decoder.decode(Test.self, from: json)

但是,如果处理标准的非多行字符串文字,则需要同时转义反斜杠和引号,导致\"My \\\"real\\\" quote\" 看起来更加混乱:

let json = "{\"resultCount\": 42, \"quote\" : \"My \\\"real\\\" quote\"}"
    .data(using: .utf8)!

【讨论】:

  • 谢谢! ...感谢其他任何人。所以问题出在字符串文字上,而不是来自后端服务的 JSON 本身(iTunes API 在许多字段中使用相同的引号)。
猜你喜欢
  • 1970-01-01
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-02
  • 2019-04-24
  • 1970-01-01
相关资源
最近更新 更多