How to Create struct for JSON Data in Swift 4

2019-09-21 21:59发布

问题:

Ok this is the link to jsonData : https://api.openweathermap.org/data/2.5/weather?q=warsaw&appid=5ca98c08c8abd2bf1fdbd601c3cf3d7e

I tried to do something like beneath but this doesn't work(of course the whole json code I have in my xcode but this is not the case, the case is how to construct the struct from the json to enable download data . Overally I want to learn how to download the data from Json, on some tutorials I saw how it works but this structure of Json data is weird.

This is what I try- of course this is only attempt with little of data

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:

This does not represent the entire data, I left some work for you

标签: json swift xcode