arrays - 如何快速解析这种 JSON 格式
问题描述
我有这种 JSON 格式:
{
"version":"7.0.19",
"fields": ["ID","pm","age","pm_0","pm_1","pm_2","pm_3","pm_4","pm_5","pm_6","conf","pm1","pm_10","p1","p2","p3","p4","p5","p6","Humidity","Temperature","Pressure","Elevation","Type","Label","Lat","Lon","Icon","isOwner","Flags","Voc","Ozone1","Adc","CH"],
"data":[[20,0.0,1,0.0,0.0,0.0,0.0,0.0,0.0,0.0,97,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,null,null,null,1413,0,"Oakdale",40.603077,-111.83612,0,0,0,null,null,0.01,1]],
"count":11880
}
但我无法弄清楚如何使用 Codable 协议来解析 json 响应。
这将是我想要的模型。
struct Point: Codable {
let pm2: String?
let latitude, longitude: Double?
let temp: String?
let iD: String?
enum CodingKeys: String, CodingKey {
case pm2 = "pm", temp = "Temperature", iD = "ID", latitude = "Lat", longitude = "Lon"
}
}
这是json的URL
https://webbfoot.com/dataa.json
解决方案
您可以使用它Codable
来解析:
struct Response: Decodable {
let version: String
let fields: [String]
let data: [[QuantumValue?]]
let count: Int
}
enter code here
enum QuantumValue: Decodable {
case float(Float), string(String)
init(from decoder: Decoder) throws {
if let int = try? decoder.singleValueContainer().decode(Float.self) {
self = .float(float)
return
}
if let string = try? decoder.singleValueContainer().decode(String.self) {
self = .string(string)
return
}
throw QuantumError.missingValue
}
enum QuantumError:Error {
case missingValue
}
}
QuantumValue
将同时处理Float
和String
并且?
将处理该null
部分。
推荐阅读
- c# - 我缺少什么统一/C#?
- amazon-web-services - AWS IAM 策略中拒绝“ListAccounts”访问
- python - TypeError:“模块”对象不可调用(随机模块)
- python-3.x - 通过 msmtp 为 crontab 发送电子邮件主题和密件抄送
- python - 带有奇怪返回函数的循环?
- c++ - 排除一个数列,使所有其他数的最大除数最多。找到被排除的索引和最大 GCD
- python-3.x - 将 rasp CCTV 视频流式传输到 TKInter 中的标签
- java - 从 HashMap 中的数组中检索值的单行代码
- metamask - 第一次 Metamask ETH 交易 Ropsten 水龙头失败
- swift - 如何从 Firestore 查询数组内的字段