所以我使用我正在尝试解析这个数据:
{"status":"success","data":{"city":"Sunnyvale","state":"California","country":"USA","location":{"type":"Point","coordinates":[-122.03635,37.36883]},"current":{"weather":{"ts":"2020-07-23T00:00:00.000Z","tp":25,"pr":1009,"hu":44,"ws":6.2,"wd":330,"ic":"02d"},"pollution":{"ts":"2020-07-23T00:00:00.000Z","aqius":7,"mainus":"p2","aqicn":2,"maincn":"p2"}}}}
我正在尝试获得aqius
结果,以及tp
...这是我现在的代码,我已经创建了这些结构:
struct Response: Codable{
let data: MyResult
let status: String
}
struct MyResult: Codable {
let city: String
}
正如你所看到的,我已经得到了城市,我可以确认它是否工作,因为当我收到请求并执行print(json.data.city)
时,它会打印"Sunnyvale“。但是我如何获得其他值呢?我一直纠结于如何在location
、current
和pollution
数据结构中获取值,我该怎么做呢?谢谢
发布于 2020-07-23 06:21:01
有一些工具可以从json字符串自动生成Codable
模型,比如:https://app.quicktype.io)
所以你的基本结构模型如下所示;
// MARK: - Response
struct Response: Codable {
let status: String
let data: DataClass
}
// MARK: - DataClass
struct DataClass: Codable {
let city, state, country: String
let location: Location
let current: Current
}
// MARK: - Current
struct Current: Codable {
let weather: Weather
let pollution: Pollution
}
// MARK: - Pollution
struct Pollution: Codable {
let ts: String
let aqius: Int
let mainus: String
let aqicn: Int
let maincn: String
}
// MARK: - Weather
struct Weather: Codable {
let ts: String
let tp, pr, hu: Int
let ws: Double
let wd: Int
let ic: String
}
// MARK: - Location
struct Location: Codable {
let type: String
let coordinates: [Double]
}
解码;
let jsonData = jsonString.data(using: .utf8)!
let model = try? JSONDecoder().decode(Response.self, from: jsonData)
https://stackoverflow.com/questions/63045390
复制相似问题