我正在使用以下模型解码对象
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的格式。我已经尝试过尝试尝试捕获,但是无法完全弄清楚如何使它正常工作(即使这是正确的选择)
我的问题是,在整数数组的情况下,如何在不引发解码器的情况下进行解码?非常感谢任何帮助。谢谢你。
答案 0 :(得分:1)
首先,您必须选择一种存储数据的方式。为简单起见,让我们将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
。
答案 1 :(得分:0)
您需要在init(from decoder: Decoder)
这是一个简单的转换,请注意类型可能不完全相同,因此兼容性由您自己安排,负担自己。
我看不到JSON,但是JSON到代码的操作非常容易,因为JSON类型在原子级别总是很简单。
我希望它能帮助...
今天过得愉快!