ios - Swift 4.2 - 解码相同 key 不同类型的 JSON

标签 ios json rest swift4

我正在使用以下模型解码一个对象

struct ACDeviceLastData {
    var DA: ACDeviceLastDataBody = ACDeviceLastDataBody()
}

struct ACDeviceLastDataBody {
    var amOn: Bool = false
    var enabledZones: [Int] = []
    var fanSpeed: Int = 0
    var mode: Int = 0
    var tempTarget: Float = 0.00
}

extension ACDeviceLastData: Decodable {
        init(from decoder: Decoder) throws {
            //Create Container
            let container = try decoder.container(keyedBy: ACDeviceCodingKeys.self)

        //Decode Data
        DA = try container.decodeIfPresent(ACDeviceLastDataBody.self, forKey: .DA) ?? ACDeviceLastDataBody()
    }
}

extension ACDeviceLastDataBody: Decodable {
    init(from decoder: Decoder) throws {
        //Create Container
        let container = try decoder.container(keyedBy: ACDeviceCodingKeys.self)

        //Decode Data
        amOn = try container.decodeIfPresent(Bool.self, forKey: .amOn) ?? false
        enabledZones = try container.decodeIfPresent([Int].self, forKey: .enabledZones) ?? []
        fanSpeed = try container.decodeIfPresent(Int.self, forKey: .fanSpeed) ?? 0
        mode = try container.decodeIfPresent(Int.self, forKey: .mode) ?? 0
        tempTarget = try container.decodeIfPresent(Float.self, forKey: .tempTarget) ?? 0.00
    }
}

问题在于 DA 的值并不总是相同的类型。它有时可以采用整数数组的格式,有时采用 ACDevieLastDataBody 的格式。我试过做一个 do-try-catch 但不太清楚如何让它工作(如果这是正确的做法)

我的问题是,当它是一个整数数组时,我将如何在解码器不抛出的情况下解码它们。非常感谢任何帮助。提前谢谢你。

最佳答案

首先,您必须选择一种存储数据的方式。为简单起见,我们将 Int 数组存储为单独的属性:

struct ACDeviceLastData {
   var DA: ACDeviceLastDataBody = ACDeviceLastDataBody()
   var DAasInts: [Int] = []
}

extension ACDeviceLastData: Decodable {
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: ACDeviceCodingKeys.self)

        if let ints: [Int] = try? (container.decodeIfPresent([Int].self, forKey: .DA) ?? []) {
            // will pass here when `DA` is null or an array of ints
            DA = ACDeviceLastDataBody()
            DAasInts = ints
        } else {
            // null is already handled above
            DA = try container.decode(ACDeviceLastDataBody.self, forKey: .DA)
            DAasInts = []
        }
    }
}

您可能希望以不同的方式表示您的数据,例如从整数数组创建 ACDeviceLastDataBody

关于ios - Swift 4.2 - 解码相同 key 不同类型的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55022856/

相关文章:

objective-c - UIAlertView 在 iPhone 上不显示

ios - iOS中的协议(protocol)方法是如何自动调用的?

angularjs - 与 promise 和 Angular 拦截器混淆

javascript - 使用 Postman 检查嵌套 JSON 中的值

iOS 应用程序 - 在 GridView 中显示来自 JSON URL 列表的图像。

javascript - 如何使用 GET 方法访问 RESTlet SuiteScript 参数

rest - 如何通过 OAuth 客户端凭据配置/访问 Bitbucket 服务器 REST API

ios - 触觉引擎 iPhone 冲击力更强

ios - 设置索引和顶点数组 openGL ES

android - 如何消除Open Weather Map API提供的JSON天气预报的歧义?