【发布时间】:2019-09-30 21:52:29
【问题描述】:
想象一个如下的数据结构,在contents 中包含一个值,该值是一个已编码的 JSON 片段。
let partial = """
{ "foo": "Foo", "bar": 1 }
"""
struct Document {
let contents: String
let other: [String: Int]
}
let doc = Document(contents: partial, other: ["foo": 1])
期望的输出
组合的数据结构应该使用contents,并编码other。
{
"contents": { "foo": "Foo", "bar": 1 },
"other": { "foo": 1 }
}
使用Encodable
Encodable 的以下实现将 Document 编码为 JSON,但它也将 contents 重新编码为字符串,这意味着它被包裹在引号中,并且所有 " 引号都转义为 \"。
extension Document : Encodable {
enum CodingKeys : String, CodingKey {
case contents
case other
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(contents, forKey: .contents)
try container.encode(other, forKey: .other)
}
}
输出
{
"contents": "{\"foo\": \"Foo\", \"bar\": 1}",
"other": { "foo": 1 }
}
encode 怎么可以直接通过contents?
【问题讨论】:
-
你可以更明确你需要什么
-
刚刚添加了一些说明????
标签: json swift encoding codable encodable