与Objective-C比较,在Swift中解析嵌套的JSON

我正在尝试在Swift中解析一些我以前在Objective-C中解析的JSON,并且遇到了一些困难。

在Objective-C中,我能够使用以下命令简单地解析它:

NSError* error;
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
Nsnumber *temp = jsonResults[@"main"][@"temp"];
Nsnumber *humidity = jsonResults[@"main"][@"humidity"];

在Swift中,到目前为止,当我尝试序列化为字典时或者在尝试访问JSON中的值时序列化为字符串时,我的代码都出现错误。

在Swift中执行此操作的正确方法是什么。这是我尝试序列化为Dictionary的版本,它给出了错误

  //assemble url query items
    components.queryItems = queryItems
    let url = components.url
    let task = URLSession.shared.dataTask(with: url!) { //open 2
    [weak self] data,response,error in
    print("heard back from task")
    guard let data = data,error == nil else { return }
    do {
    let jsonResults = try JSONSerialization.jsonObject(with: data,options: .allowFragments) as! [Dictionary:Any]
    //Gives error Dictionary' requires that 'Value' conform to 'Hashable'
    let main = jsonResults["main"] as Any
    let temp = main[3]
    completion("got here")
    } catch let error as NSError {
    print(error)
    }

以下是JSON的示例:

{"coord":{"lon":10.73,"lat":59.91},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"base":"stations","main":{"temp":49.62,"feels_like":43.45,"temp_min":48,"temp_max":52,"pressure":987,"humidity":30},"wind":{"speed":1.99,"deg":95,"gust":7},"clouds":{"all":95},"dt":1589387530,"sys":{"type":3,"id":2009047,"country":"NO","sunrise":1589337830,"sunset":1589398989},"timezone":7200,"id":3143242,"name":"Oslo County","cod":200}
taleisa 回答:与Objective-C比较,在Swift中解析嵌套的JSON

迅速,您只需要以下代码:-

型号:

struct Model: Codable {
    let coord: Coord
    let weather: [Weather]
    let base: String
    let main: Main
    let wind: Wind
    let clouds: Clouds
    let dt: Int
    let sys: Sys
    let timezone,id: Int
    let name: String
    let cod: Int
}

struct Clouds: Codable {
    let all: Int
}

struct Coord: Codable {
    let lon,lat: Double
}

struct Main: Codable {
    let temp,feelsLike: Double
    let tempMin,tempMax,pressure,humidity: Int

    enum CodingKeys: String,CodingKey {
        case temp
        case feelsLike = "feels_like"
        case tempMin = "temp_min"
        case tempMax = "temp_max"
        case pressure,humidity
    }
}

struct Sys: Codable {
    let type,id: Int
    let country: String
    let sunrise,sunset: Int
}

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

struct Wind: Codable {
    let speed: Double
    let deg,gust: Int
}

解析:

do {
    let model = try JSONDecoder().decode(Model.self,from: data)
} catch {
    print(error.localizedDescription)
}
本文链接:https://www.f2er.com/2362355.html

大家都在问