Imagine a data structure as follows, containing a value in contents
that is an already encoded JSON fragment.
let partial = """
{ "foo": "Foo", "bar": 1 }
"""
struct Document {
let contents: String
let other: [String: Int]
}
let doc = Document(contents: partial, other: ["foo": 1])
Desired output
The combined data structure should use contents
as is and encode other
.
{
"contents": { "foo": "Foo", "bar": 1 },
"other": { "foo": 1 }
}
Using Encodable
The following implementation of Encodable
encodes Document
as JSON, however it also re-encodes contents
into a string, meaning it is wrapped in quotes and has all "
quotes escaped into \"
.
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)
}
}
Output
{
"contents": "{\"foo\": \"Foo\", \"bar\": 1}",
"other": { "foo": 1 }
}
How can encode
just pass through contents
as is?