JSON 可解码 swift 4

JSON decodable swift 4

我在为以下 JSON 创建 public 结构时遇到了麻烦。我正在尝试提取温度和湿度。我试图提取以下 JSON 但我认为我在识别每个变量的方式上遇到了问题。

这是JSON:

{"coord":{"lon":-82.26,"lat":27.76},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"base":"stations","main":{"temp":66.24,"pressure":1021,"humidity":63,"temp_min":62.6,"temp_max":69.8},"visibility":16093,"wind":{"speed":8.05,"deg":80},"clouds":{"all":90},"dt":1523500500,"sys":{"type":1,"id":726,"message":0.0051,"country":"US","sunrise":1523531237,"sunset":1523577156},"id":420006939,"name":"Brandon","cod":200}

这是结构

public struct Page: Decodable {

private enum CodingKeys : String, CodingKey {
    case coord = "coord", weather = "weather", mainz = "main", visibility = "visibility", wind = "wind", clouds = "clouds", dt = "dt", sys = "sys", id = "id", name = "name", cod = "cod"}

let coord: String
let weather: [String]
let mainz: String
let visibility: Int
let wind: String
let clouds: String
let dt: Int
let sys: String
let id: Int
let name: String
let cod: Int


public struct Main: Decodable {
    private enum CodingKeys : String, CodingKey {
        case temp = "temp", pressure = "pressure",humidity = "humidity", temp_min = "temp_min", temp_max = "temp_max"
    }
    let temp: Int
    let pressure: Int
    let humidity: Int
    let temp_min: Int
    let temp_max: Int
}

...以及我正在使用解码的代码...

     //             Make the POST call and handle it in a completion handler
    let task =  session.dataTask(with: components.url!, completionHandler: {(data, response, error) in
        guard let data = data else { return }
        do
        {

            let result = try JSONDecoder().decode(Page.self, from: data)

            for main in result.mainz {
               print(main.humidity)

            }

        }catch

        {print("Figure it out")

        }



    })
    task.resume()

创建结构来捕捉你想要的任何东西。例如,如果您对温度和坐标感兴趣,请为它们创建结构:

struct WeatherTemperature: Codable {
    let temp: Double
    let pressure: Double
    let humidity: Double
    let tempMin: Double
    let tempMax: Double
}

struct WeatherCoordinate: Codable {
    let latitude: Double
    let longitude: Double

    enum CodingKeys: String, CodingKey {
        case latitude = "lat"
        case longitude = "lon"
    }
}

然后为整个响应创建一个结构:

struct ResponseObject: Codable {
    let coord: WeatherCoordinate
    let main: WeatherTemperature
}

注意,我只为我关心的键创建属性。

然后解码:

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

do {
    let responseObject = try decoder.decode(ResponseObject.self, from: data)
    print(responseObject.coord)
    print(responseObject.main)
} catch {
    print(error)
}

结果是:

WeatherCoordinate #1(latitude: 27.760000000000002, longitude: -82.260000000000005)

WeatherTemperature #1(temp: 66.239999999999995, pressure: 1021.0, humidity: 63.0, tempMin: 62.600000000000001, tempMax: 69.799999999999997)

显然,添加您关心的任何其他 structures/properties,但希望这能说明这个想法。

请注意,我不想让 JSON 决定我的 属性 名称,因此,例如,我为我的解码器指定了一个关键解码策略以从 JSON 转换snake_case 到 Swift 驼峰式。

我也喜欢更长的 属性 名字,所以我想要更具表现力的名字(latitudelongitude 而不是 latlon),我为那些定义了 CodingKeys。但是在这个分数上做任何你想做的事情。