Swift 4中的JSON解析与复杂的&嵌套数据

时间:2017-10-08 22:06:22

标签: json swift

我目前正在尝试使用https://openweathermap.org中的JSON制作天气应用程序,但我在JSON文件中遇到了天气部分问题。我不确定如何访问对象内的'id'值。

{
  "base": "stations",
  "clouds": {
    "all": 36
  },
  "cod": 200,
  "coord": {
    "lat": 51.51,
    "lon":
      -0.13
  },
  "dt": 1507497600,
  "id": 2643743,
  "main": {
    "humidity": 82,
    "pressure": 1021,
    "temp": 10.65,
    "temp_max": 13,
    "temp_min": 9
  },
  "name": "London",
  "sys": {
    "country": "GB",
    "id": 5091,
    "message": 0.0036,
    "sunrise": 1507443264,
    "sunset": 1507483213,
    "type": 1
  },
  "visibility": 10000,
  "weather": [{
    "description": "scattered clouds",
    "icon": "03n",
    "id": 802,
    "main": "Clouds"
  }],
  "wind": {
    "deg": 200,
    "speed": 1.5
  }
}

我如何能够获取数据。在我的快速代码中,我使用的结构符合swift 4中新的“可编码”协议。

// all structures for the data
struct CurrentLocalWeather: Codable {
    let base: String
    let clouds: clouds
    let cod: Int
    let coord: coord
    let dt: Int
    let id: Int
    let main: main
    let name: String
    let sys: sys
    let visibility: Int
    let weather: [weather]
    let wind: wind
    }  

struct clouds: Codable {
    let all: Int
}

struct coord: Codable {
    let lat: Double
    let lon: Double
}

struct main: Codable {
    let humidity: Double
    let pressure: Double
    let temp: Double
    let temp_max: Double
    let temp_min: Double
}

struct sys: Codable {
    let country: String
    let id: Int
    let message: Double
    let sunrise: Double
    let sunset: Double
    let type: Int
}

struct weather: Codable {
    let description: String
    let icon: String
    let id: Int
    let main: String
}

struct wind: Codable {
    let deg: Double
    let speed: Double
}

// Get data from weather server
func getCurrentWeatherData() {

        let jsonUrlString = "https://api.openweathermap.org/data/2.5/weather?id=2643743&units=metric&APPID=fdf04e9483817ae2fa77048f7e6705e8"

        guard let url = URL(string: jsonUrlString) else { return }

        URLSession.shared.dataTask(with: url) { (data, response, err) in

            guard let data = data else { return }

            do {
                let decoder = JSONDecoder()
                decoder.dateDecodingStrategy = .iso8601

                let json = try decoder.decode(CurrentLocalWeather.self, from: data)

                print("Data Successfully Retrieved!\nServer Response: \(json.cod)\nLocation: \(json.name)")

                DispatchQueue.main.async() {
                    // Any of the following allows me to access the data from the JSON 
                    self.locationLabel.text = "\(json.name)"
                    self.temperatureLabel.text = "Currently: \(json.main.temp)ºC"
                    self.highTemperatureLabel.text = "High: \(json.main.temp_max)ºC"
                    self.lowTemperatureLabel.text = "Low: \(json.main.temp_min)ºC"
                    self.sunriseLabel.text = "\(self.convertFromUnixToNormal(time: json.sys.sunrise))"
                    self.sunsetLabel.text = "\(self.convertFromUnixToNormal(time: json.sys.sunset))"
                    self.humidityLabel.text = "Humidity: \(json.main.humidity)%"
                    self.pressureLabel.text = "Pressure: \(json.main.pressure) hPa"
                    self.windSpeedLabel.text = "Wind Speed: \(json.wind.speed) km/h"


                }
            } catch let jsonErr {
                print("Error: \(jsonErr)")
            }

        }.resume()
    }

2 个答案:

答案 0 :(得分:5)

您需要正确识别您的json字符串并提供解码所需的所有结构。只需查看json,您就可以了解必要的结构以正确解码它:

struct CurrentLocalWeather: Codable {
    let base: String
    let clouds: Clouds
    let cod: Int
    let coord: Coord
    let dt: Int
    let id: Int
    let main: Main
    let name: String
    let sys: Sys
    let visibility: Int
    let weather: [Weather]
    let wind: Wind
}
struct Clouds: Codable {
    let all: Int
}
struct Coord: Codable {
    let lat: Double
    let lon: Double
}
struct Main: Codable {
    let humidity: Int
    let pressure: Int
    let temp: Double
    let tempMax: Int
    let tempMin: Int
    private enum CodingKeys: String, CodingKey {
        case humidity, pressure, temp, tempMax = "temp_max", tempMin = "temp_min"
    }
}
struct Sys: Codable {
    let country: String
    let id: Int
    let message: Double
    let sunrise: UInt64
    let sunset: UInt64
    let type: Int
}
struct Weather: Codable {
    let description: String
    let icon: String
    let id: Int
    let main: String
}
struct Wind: Codable {
    let deg: Int
    let speed: Double
}
let weatherData = Data("""
{"base"  : "stations",
 "clouds": { "all": 36 },
 "cod"   : 200,
 "coord" : { "lat": 51.51,
             "lon": -0.13},
 "dt": 1507497600,
 "id": 2643743,
 "main": {
        "humidity": 82,
        "pressure": 1021,
        "temp": 10.65,
        "temp_max": 13,
        "temp_min": 9},
 "name": "London",
 "sys": {
        "country": "GB",
        "id": 5091,
        "message": 0.0036,
        "sunrise": 1507443264,
        "sunset": 1507483213,
        "type": 1 },
 "visibility": 10000,
 "weather": [{
    "description": "scattered clouds",
    "icon": "03n",
    "id": 802,
    "main": "Clouds"}],
 "wind": {
    "deg": 200,
    "speed": 1.5
    }
 }
""".utf8)
let decoder = JSONDecoder()

do {
    let currentLocalWeather = try decoder.decode(CurrentLocalWeather.self, from: weatherData)
    print(currentLocalWeather)   // "CurrentLocalWeather(base: "stations", clouds: __lldb_expr_367.Clouds(all: 36), cod: 200, coord: __lldb_expr_367.Coord(lat: 51.509999999999998, lon: -0.13), dt: 1507497600, id: 2643743, main: __lldb_expr_367.Main(humidity: 82, pressure: 1021, temp: 10.65, temp_max: 13, temp_min: 9), name: "London", sys: __lldb_expr_367.Sys(country: "GB", id: 5091, message: 0.0035999999999999999, sunrise: 1507443264, sunset: 1507483213, type: 1), visibility: 10000, weather: [__lldb_expr_367.Weather(description: "scattered clouds", icon: "03n", id: 802, main: "Clouds")], wind: __lldb_expr_367.Wind(deg: 200, speed: 1.5))\n"
} catch {
    print(error)
}

答案 1 :(得分:1)

您需要在JSON中定义自定义类型的类型,例如天气,云,coord等。我建议查看documentation中的示例。

在示例中,Landmark类型的“location”属性为Coordinate类型。您甚至可以在示例中使用Coordinate类型作为JSON对象中的coord属性。但是,您需要使用CodingKey协议提供正确的密钥,该协议也在documentation中进行了描述。例如,您的Coordinate类型可能如下所示:

struct Coordinate: Codable {
    var latitude: Double
    var longitude: Double

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