关于Int和String的swift json解析[重复]。

问题描述 投票:0回答:1

至于我收到的JSON,有时看起来是这样的。

                    "doseQuantity": {
                        "value": ""
                    }

但有时它看起来像:

                   "doseQuantity": {
                        "value": 1
                    }

元素值可能是Int或String.如果我这样解析:

                 struct doseQuantity: Codable {
                         let value: Int?
                    }

结果是: "预计要解码Int,但却发现了一个Stringdata。"所以我只是想知道如果我想解析这个JSON,我应该怎么做。

json swift string parsing int
1个回答
-1
投票

使用通用性,并在解码这个模型时提供类型。

struct DoseQuantity<T: Codable>: Codable {
    let value: T?
}

像这样使用。

do {
    let doseQuantity = try JSONDecoder().decode(DoseQuantity<Int>.self, from: data)
    print(doseQuantity)
} catch {
    print(error)
}

或者你可以把这两种情况嵌套在 try catch 块这样。

do {
    let doseQuantity = try JSONDecoder().decode(DoseQuantity<Int>.self, from: data)
    print(doseQuantity)
} catch {
    do {
        let doseQuantity = try JSONDecoder().decode(DoseQuantity<String>.self, from: data)
        print(doseQuantity)
    } catch {
        print(error)
    }
}

注意:这个解决方案假设在可编码结构中没有超过几个不同类型的属性。如果有多个类型变化的属性,你可以使用自定义的 init(decoder:) 这将是更好的设计,而不是拥有一个 try catch 树木。

© www.soinside.com 2019 - 2024. All rights reserved.