【问题标题】:Xcode confused with IQAir Api ParsingXcode 与 IQAir Api 解析混淆
【发布时间】:2020-07-23 01:13:40
【问题描述】:

所以我用我试图解析这些数据:

{"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
}

如您所见,我得到了 city,并且我可以确认它有效,因为当我收到请求和 print(json.data.city) 时,它会打印“Sunnyvale”。 但是我将如何获得其他值?我一直坚持如何在 location 、 current 和 pollution 数据结构中获取值,我该怎么做? 谢谢

【问题讨论】:

标签: json swift xcode api


【解决方案1】:

有些工具可以从 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)

【讨论】:

  • 兄弟,非常感谢!这是一个了不起的工具会使用它
猜你喜欢
  • 2017-01-19
  • 2011-12-13
  • 1970-01-01
  • 2013-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
  • 1970-01-01
相关资源
最近更新 更多