【发布时间】: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