You need to enable JavaScript to run this app. 如何配置Decodable类型JSON结构体以跳过nil值或设置默认值
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Decodable类型JSON结构体以跳过nil值或设置默认值

现有代码说明

你当前的实现已经可以自动处理字段为nil或者字段缺失的场景:因为你将value声明为Double?可选类型,当JSON中对应字段返回null、或者字段不存在时,解析后value会自动赋值为nil,不会触发解析失败,相当于自动保留nil状态。

如果你需要字段为nil时设置固定默认值,有两种常用实现方案

方案1:手动实现解码初始化方法(灵活度最高)

你可以自行实现Decodable协议要求的初始化方法,使用decodeIfPresent方法尝试解析,解析失败时赋值自定义默认值即可:

struct Information: Decodable {
    public let value: Double
    
    private enum CodingKeys: String, CodingKey {
        case value
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        // 解析失败时默认赋值为0,可根据业务需求修改为其他默认值
        value = try container.decodeIfPresent(Double.self, forKey: .value) ?? 0
    }
}

方案2:属性包装器实现(适合多字段复用相同默认值规则)

如果有多个同类型字段需要统一设置默认值,可以封装通用属性包装器减少重复代码:

// 定义默认值为0的Double类型属性包装器
@propertyWrapper
struct DefaultZero: Decodable {
    var wrappedValue: Double
    
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        wrappedValue = try container.decodeIfPresent(Double.self) ?? 0
    }
    
    init() {
        wrappedValue = 0
    }
}

// 业务结构体使用示例
struct Information: Decodable {
    @DefaultZero public var value: Double
}

如果你需要完全忽略某个字段

只要不把对应的字段名加入CodingKeys枚举即可,解析时会自动跳过该字段的处理。

内容的提问来源于stack exchange,提问作者helloworld12345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 22:45:04