首页 > 解决方案 > 如何快速解析这种 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

标签: arraysjsonswiftcodable

解决方案


您可以使用它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将同时处理FloatString并且?将处理该null部分。


推荐阅读