gpt4 book ai didi

json - Swift 可编码 : encode nil as an empty object

转载 作者:行者123 更新时间:2023-12-02 16:06:07 25 4
gpt4 key购买 nike

如何将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com