如果使用 JSONDecoder 需要解析的 JSON 中含有一个 null 对象,应该如何编写 Codable 结构体?

如果 JSON 中含有一个 null 对象,可以在 Codable 结构体中将该属性声明为可选类型,并使用 'decodeIfPresent' 方法进行解码。以下是一个示例:

struct MyStruct: Codable {
    var nullableProperty: Int?
    
enum CodingKeys: String, CodingKey {
        case nullableProperty = "nullable_property"
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        nullableProperty = try container.decodeIfPresent(Int.self, forKey: .nullableProperty)
    }
}

在上面的示例中,'nullableProperty' 属性被声明为可选的 Int 类型。在 'init(from:)' 方法中,我们使用 'decodeIfPresent' 方法从 JSON 中解码该属性。如果 JSON 中存在 'null' 值,则 'decodeIfPresent' 方法返回 'nil',并将 'nullableProperty' 设置为 'nil'。如果 JSON 中不存在该属性,则 'decodeIfPresent' 方法也会返回 'nil',并且 'nullableProperty' 保持为 'nil'。

Swift Codable: 如何解析包含 Null 对象的 JSON 数据

原文地址: https://www.cveoy.top/t/topic/okyw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录