如何在Swift 4中为JSON数据创建结构

时间:2018-04-12 16:25:33

标签: json swift xcode

好的,这是jsonData的链接:https://api.openweathermap.org/data/2.5/weather?q=warsaw&appid=5ca98c08c8abd2bf1fdbd601c3cf3d7e

我尝试做类似下面的事情,但是这不起作用(当然我的xcode中有整个json代码,但事实并非如此,案例是如何从json构造结构以启用下载数据总的来说我想学习如何从Json下载数据,在一些教程中我看到它是如何工作的,但这种Json数据结构很奇怪。

这是我尝试的 - 当然这只是少量数据的尝试

struct Weather: Codable {

let weather : [cos]
let base: String




}

struct cos:Codable {

let main: String

}

let url = URL(string:  "https://api.openweathermap.org/data/2.5/weather?q=warsaw&appid=5ca98c08c8abd2bf1fdbd601c3cf3d7e")

override func viewDidLoad() {
    super.viewDidLoad()
   json()
}

func json(){

    guard let downloadURL = url else {return}

    URLSession.shared.dataTask(with: downloadURL) { (data, response, error) in



        guard let data = data, error == nil, response != nil
            else {
                print("zle cos")
                return

        }
        print("downloaded")
        do{

            let downloaded = try JSONDecoder().decode([Weather].self, from: data)
            print("ok")

            print(downloaded[0].)




        }catch {
            print("error")


        }
    }.resume()


}

1 个答案:

答案 0 :(得分:0)

这并不代表整个数据,我为你留下了一些工作

请仔细阅读JSON,所有词典({})都可以解码为结构,双引号中的所有值都是String,浮点数值是Double,其他Int,以1523开头的Int日期...可以使用适当的日期策略解码为Date

let jsonString = """
{"coord":{"lon":21.01,"lat":52.23},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"base":"stations","main":{"temp":294.15,"pressure":1012,"humidity":52,"temp_min":294.15,"temp_max":294.15},"visibility":10000,"wind":{"speed":6.7,"deg":90},"clouds":{"all":0},"dt":1523548800,"sys":{"type":1,"id":5374,"message":0.0023,"country":"PL","sunrise":1523504666,"sunset":1523554192},"id":756135,"name":"Warsaw","cod":200}
"""

struct Root : Decodable {
    let coord : Coordinate
    let weather : [Weather]
    let base : String
    let main : Main
    let dt : Date
}

struct Coordinate : Decodable {
    let lat, lon : Double
}

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

struct Main : Decodable {
    let temp, tempMin, tempMax : Double
    let pressure, humidity : Int
}
let data = Data(jsonString.utf8)
do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    decoder.dateDecodingStrategy = .secondsSince1970
    let result = try decoder.decode(Root.self, from: data)
    print(result)
} catch { print(error) }