[英]Swift: custom key-value encoding with Encodable conformance in struct
struct Struct: Encodable {
let key: String
let value: String
}
let aStruct = Struct(key: "abc", value: "xyz")
Given this struct and the default Encodable
conformance provided, JSON encoding produces鉴于此结构和提供的默认
Encodable
一致性,JSON 编码产生
{
key = abc;
value = xyz;
}
whereas instead I'd like to to encode it to而相反,我想将其编码为
{
abc = xyz;
}
how do I conform this struct to Encodable
to end up with this result?我如何使这个结构符合
Encodable
以得到这个结果?
Implement encode(to encoder: Encoder)
and encode the struct as single dictionary实现
encode(to encoder: Encoder)
并将结构编码为单个字典
struct Struct: Encodable {
let key: String
let value: String
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode([key:value])
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.