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

标签 json swift codable foundation encodable

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

相关文章:

ios - 支持从右到左的纯布局

json - 序列化 JSON "keyNotFound"时出错

json - 使用可配置键的 Swift 4 JSON 解码

php - 如何通过ajax将mysql结果作为jSON传递

javascript - 未捕获的类型错误 : undefined is not a function when using JSON object with name

java - 在 Spring Controller 中使用 JSON Patch 时出现 HttpMessageNotReadableException

javascript - 使用 JavaScript 的 md5 的较短版本..?

ios - Collection View 为空时如何显示消息

swift - 是第一个(其中 :) Method always O(n) or it can be O(1) with usage of Set or Dictionary?

ios - Codable:手动处理一个键