我在可编码解析方面遇到问题...这是我的示例代码:
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/