JSON可解码swift 4

JSON可解码swift 4,json,swift4,decode,xcode9.2,Json,Swift4,Decode,Xcode9.2,我在为下面的JSON创建公共结构时遇到了麻烦。我正试图提取温度和湿度。我试图提取以下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

我在为下面的JSON创建公共结构时遇到了麻烦。我正试图提取温度和湿度。我试图提取以下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)
}
这导致:

天气坐标#1(纬度:27.760000000000002,经度:-82.260000000000005)

天气温度#1(温度:66.2399999995,压力:1021.0,湿度:63.0,最低温度:62.60000000000001,最高温度:69.79999997)

显然,添加您关心的任何其他结构/属性,但希望这能说明这个想法

注意,我不想让JSON命令我的属性名,因此,例如,我为解码器指定了一个密钥解码策略,以便将JSON snake_case转换为Swift camelCase


我也喜欢较长的属性名称,因此,如果我想要更具表现力的名称(
纬度
经度
,而不是
纬度
经度
),我就为它们定义了
编码键。但在这一点上,你想做什么就做什么。

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

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)
}
这导致:

天气坐标#1(纬度:27.760000000000002,经度:-82.260000000000005)

天气温度#1(温度:66.2399999995,压力:1021.0,湿度:63.0,最低温度:62.60000000000001,最高温度:69.79999997)

显然,添加您关心的任何其他结构/属性,但希望这能说明这个想法

注意,我不想让JSON命令我的属性名,因此,例如,我为解码器指定了一个密钥解码策略,以便将JSON snake_case转换为Swift camelCase


我也喜欢较长的属性名称,因此,如果我想要更具表现力的名称(
纬度
经度
,而不是
纬度
经度
),我就为它们定义了
编码键。但在这一点上,你想怎么做就怎么做。

请看第一件事,你需要知道如何阅读JSON。看看JSON中的第一件事:
“coord”:{“lon”:-82.26,“lat”:27.76}
。嗯,那个叫做“坐标”的东西不是字符串;这是一本字典。但您正在以字符串形式键入
coord
。所以这永远不会成功我可以继续,但你是需要继续的人。考虑每件事的类型。请看第一件事是你需要知道如何阅读JSON。看看JSON中的第一件事:
“coord”:{“lon”:-82.26,“lat”:27.76}
。嗯,那个叫做“坐标”的东西不是字符串;这是一本字典。但您正在以字符串形式键入
coord
。所以这永远不会成功我可以继续,但你是需要继续的人。想一想每件事情的类型。谢谢你的分解。它不仅帮助我回答了这个问题,而且还帮助我理解了未来解码JSON的最佳方式。再次感谢,谢谢你的支持。它不仅帮助我回答了这个问题,而且还帮助我理解了未来解码JSON的最佳方式。再次感谢。