json - 解析时 JSON 无效\n(带引号的)字符串

标签 json swift codable jsondecoder

我在可编码解析方面遇到问题...这是我的示例代码:

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)

这里一切都按预期工作,并且创建了测试对象。<​​/p>

现在我的后端向我发送中间带有引号的引号字符串...以这种形式(请注意\"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: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in object around character 4." UserInfo={NSDebugDescription=No string key for value in object around character 4.})))

有办法解决这个问题吗?

最佳答案

要在 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\\\"看起来更令人困惑引用\":

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

关于json - 解析时 JSON 无效\n(带引号的)字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54041146/

相关文章:

Python 无法加载由 json.dump 创建的 JSON

javascript - 使用 Node 和 Express 4 使用 res.json 中的数据时出现非法 token

swift - 当默认模式兼容所有类别时,AVAudioSession 中其他模式的用途是什么?

ios - Xcode项目环境变量

swift - 在 Swift 中同时实现 Codable 和 NSManagedObject

json - 如何通过 Swift 4 的 Decodable 协议(protocol)使用自定义键?

mysql - 在 MySQL 中正确存储电子邮件(额外/非必要) header 作为 JSON

json - 使用jQuery获取json数据返回无效标签错误

ios - 我应该在哪个线程中发送分析数据

json - Codable 和 JSON 的问题