You need to enable JavaScript to run this app. Codable结构体搭配Measurement<Unit>的Dimension单位JSON存读问题
优惠活动
大模型
产品
解决方案
定价
更多

Codable结构体搭配Measurement<Unit>的Dimension单位JSON存读问题

Swift Dimension单位JSON序列化方案

问题根因

系统Measurement<Unit>类型虽然默认声明了Codable支持,但默认序列化逻辑存在两个问题:

  1. 会生成包含value、unit的嵌套结构,unit字段是包含单位类型、符号的复杂结构体,不是你需要的简单字符串格式
  2. 泛型如果使用基类Unit而非具体的UnitMass/UnitVolume等子类,解码时无法确定单位所属维度,会直接解码失败

实现方案

你要的"unit": "kg"自动映射UnitMass.kilogram的需求完全可以实现,不需要自行编写单位规则,只需要自定义结构体的编解码逻辑,配置单位符号映射表即可。

场景1:仅存储单位类型(无关联度量值)

如果你的unit字段只需要存单位,不需要关联数值,修改结构体实现如下:

struct Item: Hashable, Identifiable, Codable {
    var id: Int
    var name: String
    var price: Int
    var unit: Unit
    
    enum CodingKeys: String, CodingKey {
        case id, name, price, unit
    }
    
    // 单位映射表,新增支持单位直接在这里加即可
    private static let unitSymbolMap: [String: Unit] = [
        "kg": UnitMass.kilograms,
        "g": UnitMass.grams,
        "L": UnitVolume.liters,
        "ml": UnitVolume.milliliters
    ]
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
        name = try container.decode(String.self, forKey: .name)
        price = try container.decode(Int.self, forKey: .price)
        let symbol = try container.decode(String.self, forKey: .unit)
        guard let unit = Self.unitSymbolMap[symbol] else {
            throw DecodingError.dataCorruptedError(
                forKey: .unit, 
                in: container, 
                debugDescription: "不支持的单位符号:\(symbol)"
            )
        }
        self.unit = unit
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(id, forKey: .id)
        try container.encode(name, forKey: .name)
        try container.encode(price, forKey: .price)
        try container.encode(unit.symbol, forKey: .unit)
    }
}

对应的JSON格式:

[
    {
        "id": 1,
        "name": "Test",
        "price": 195,
        "unit": "kg"
    }
]

场景2:需要存储带数值的度量值(Measurement类型)

如果你的unit属性需要同时存数值和单位,修改结构体实现如下:

struct Item: Hashable, Identifiable, Codable {
    var id: Int
    var name: String
    var price: Int
    var unit: Measurement<Unit>
    
    enum CodingKeys: String, CodingKey {
        case id, name, price, unitValue, unitSymbol
    }
    
    private static let unitSymbolMap: [String: Unit] = [
        "kg": UnitMass.kilograms,
        "g": UnitMass.grams,
        "L": UnitVolume.liters,
        "ml": UnitVolume.milliliters
    ]
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
        name = try container.decode(String.self, forKey: .name)
        price = try container.decode(Int.self, forKey: .price)
        let value = try container.decode(Double.self, forKey: .unitValue)
        let symbol = try container.decode(String.self, forKey: .unitSymbol)
        guard let unit = Self.unitSymbolMap[symbol] else {
            throw DecodingError.dataCorruptedError(
                forKey: .unitSymbol, 
                in: container, 
                debugDescription: "不支持的单位符号:\(symbol)"
            )
        }
        self.unit = Measurement(value: value, unit: unit)
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(id, forKey: .id)
        try container.encode(name, forKey: .name)
        try container.encode(price, forKey: .price)
        try container.encode(unit.value, forKey: .unitValue)
        try container.encode(unit.unit.symbol, forKey: .unitSymbol)
    }
}

对应的JSON格式:

[
    {
        "id": 1,
        "name": "Test",
        "price": 195,
        "unitValue": 2.5,
        "unitSymbol": "kg"
    }
]

后续需要新增支持的单位,只需要在unitSymbolMap中添加对应符号和系统单位实例的映射即可,所有单位的转换、计算规则全部复用系统Dimension的原生实现,不需要额外开发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 06:36:02