struct Struct: Encodable {
let key: String
let value: String
}
let aStruct = Struct(key: "abc", value: "xyz")
给出此结构并提供默认的Encodable
一致性,JSON编码就会产生
{
key = abc;
value = xyz;
}
相反,我想将其编码为
{
abc = xyz;
}
我如何使此结构符合Encodable
才能得到此结果?
答案 0 :(得分:3)
实施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])
}
}