如何解码可变类型的JSON数据字段?

时间:2018-09-15 11:28:08

标签: json swift api decodable

我正在从API接收JSON数据,但是有些字段有时是字符串,而其他时候是整数。最好的解决方案是什么?

这是我的解码代码:

public struct Nutriments {
    public let energy: String?
    public let energyServing: String?
    public let energy100g: String?

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        energy = try container.decodeIfPresent(String.self, forKey: .energy)
        energy100g = try container.decodeIfPresent(String.self, forKey: .energy100g)
        energyServing = try container.decodeIfPresent(String.self, forKey: .energyServing)
        }
}

JSON示例:

"nutriments": {
        "energy_100g": 8.97,
        "energy_serving": "55",
        "energy": "7"
}

和其他类似情况:

"nutriments": {
        "energy_100g": "8.97",
        "energy_serving": 55,
        "energy": 7
}

2 个答案:

答案 0 :(得分:1)

首先责怪该服务的所有者发送不一致的数据。

要解码这两种类型,您可以在init方法中检查类型。

至少API似乎发送了所有密钥,因此您可以将所有结构成员声明为非可选

public struct Nutriments {

    public let energy: String
    public let energyServing: String
    public let energy100g: String

    public init(from decoder: Decoder) throws {      
        let container = try decoder.container(keyedBy: CodingKeys.self)
        do { energy = try container.decode(String.self, forKey: .energy) }
        } catch DecodingError.typeMismatch { energy = String(try container.decode(Int.self, forKey: .energy)) }
        do { energy100g = try container.decode(String.self, forKey: .energy100g) }
        } catch DecodingError.typeMismatch { energy100g = String(try container.decode(Int.self, forKey: .energy100g)) }
        do { energyServing = try container.decode(String.self, forKey: .energyServing) }
        } catch DecodingError.typeMismatch { energyServing = String(try container.decode(Int.self, forKey: .energyServing)) }
    }
}

答案 1 :(得分:0)

一种解决方案是在Double上声明一个自定义包装器,该包装器知道如何从字符串或双打中解码自己:

struct DoubleLike: Decodable {
    public let value: Double

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        do {
            value = try container.decode(Double.self)
        } catch DecodingError.typeMismatch {
            let valueString = try container.decode(String.self)
            if let dbl = Double(valueString) {
                value = dbl
            } else {
                throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Could not convert \(valueString) to Double"))
            }
        }
    }
}

您将能够在您的结构中轻松使用它:

struct Nutriments: Decodable {
    public let energy: DoubleLike
    public let energyServing: DoubleLike
    public let energy100g: DoubleLike

    enum CodingKeys: String, CodingKey {
        case energy
        case energyServing = "energy_serving"
        case energy100g = "energy_100g"
    }
}

此解决方案具有可伸缩性的优点,缺点是您始终需要先提取.value属性,然后才能使用解码后的double。

另一种解决方案是编写自己的Decoder实现,但这可能不值得。