如何将 nil 属性编码为空 JSON 对象?
struct Foo: Encodable {
let id = 10
let bar: Bar? = nil
}
struct Bar: Encodable {
let number: Int
}
let data = try! JSONEncoder().encode(Foo())
print(String(data: data, encoding: .utf8)!)
打印出来:
"{"id":7}"
我想要的是:
"{"id":7, "bar":{}}"
最佳答案
当 bar = nil
encoder
引入一个没有属性的空结构
struct Foo: Encodable {
let id = 10
let bar: Bar? = nil
enum CodingKeys : String, CodingKey {
case id
case bar
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
if let bar = bar {
try container.encode(bar, forKey: .bar)
}
else {
try container.encode(Empty(), forKey: .bar)
}
}
}
struct Bar: Encodable {
let number: Int
}
struct Empty: Encodable {
}
关于json - Swift 可编码 : encode nil as an empty object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69347300/