Swift 4解析json数字键,带1+;氮量
我仍在学习Swift 4中JSON解析的新功能 我能够构建一个结构并获取温度键,但是泵和其他类似的项目是数字字符串,可以是1到n。将它们解析为数组或字典的最佳方法是什么。我会假设一个for循环Swift 4解析json数字键,带1+;氮量,json,swift4,Json,Swift4,我仍在学习Swift 4中JSON解析的新功能 我能够构建一个结构并获取温度键,但是泵和其他类似的项目是数字字符串,可以是1到n。将它们解析为数组或字典的最佳方法是什么。我会假设一个for循环 public struct ServerReponse: Codable { let temperature: Temperature let circuit: Circuit } public struct Circuit: Codable { let number: I
public struct ServerReponse: Codable {
let temperature: Temperature
let circuit: Circuit
}
public struct Circuit: Codable {
let number: Int
let numberStr: String
let name: String
let circuitFunction: String
let status: Int
let freeze: Int
let delay: Int
let friendlyName: String
let light: Light?
}
public struct Light: Codable {
let pump: Int
let position: Int
let colorStr: String
let color: Int
let colorSet: Int
let colorSetStr: String
let prevColor: Int
let prevColorStr: String
let colorSwimDelay: Int
let mode: Int
let modeStr: String
}
public struct Temperature : Codable {
let poolTemp: Int
let airTemp: Int
let poolSetPoint: Int
let heaterActive: Int
}
...
let poolData = try? JSONDecoder().decode(ServerReponse.self, from: data)
print(poolData?.temperature)
我在解析下一节“电路”时遇到问题,其中可能有1到多个数字键,然后电路会在每一个数字键下面自行构造
下面是我正在使用的一些JSON
键
电路的值是一个字典
如果需要通过数字快速访问,请将对象解码为[String:Circuit]
public struct ServerReponse: Codable {
let temperature: Temperature
let circuit: [String:Circuit]
}
如果数组更合适,则编写一个自定义初始值设定项,该初始值设定项还将值映射到数组
public struct ServerReponse: Codable {
let temperature: Temperature
let circuits: [Circuit]
private enum CodingKeys: String, CodingKey { case temperature, circuits = "circuit"}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
temperature = try container.decode(Temperature.self, forKey: .temperature)
let circuitData = try container.decode([String:Circuit].self, forKey: .circuits)
circuits = Array(circuitData.values).sorted(by: {$0.number < $1.number})
}
}
公共结构ServerResponse:Codable{
让温度:温度
let电路:[电路]
私有枚举编码键:字符串,编码键{case temperature,circuits=“circuit”}
public init(来自解码器:解码器)抛出{
let container=try decoder.container(keyedBy:CodingKeys.self)
温度=尝试容器。解码(temperature.self,forKey:.temperature)
让circuitData=try container.decode([String:Circuit].self,forKey:.circuits)
电路=数组(circuitData.values)。排序(按:{$0.number<$1.number})
}
}
public struct ServerReponse: Codable {
let temperature: Temperature
let circuits: [Circuit]
private enum CodingKeys: String, CodingKey { case temperature, circuits = "circuit"}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
temperature = try container.decode(Temperature.self, forKey: .temperature)
let circuitData = try container.decode([String:Circuit].self, forKey: .circuits)
circuits = Array(circuitData.values).sorted(by: {$0.number < $1.number})
}
}