Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

ios - Creation problem with appropriate struct for URL data in JSON format. Source URL in example

Url source code : https://api.openweathermap.org/data/2.5/weather?q=warsaw&appid=5ca98c08c8abd2bf1fdbd601c3cf3d7e

I tried this code but it's not correct, i have problem with writing appropriate struct.

    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()    
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Please read the JSON carefully, all dictionaries ({}) can be decoded into a struct, all values in double quotes are String, floating point numeric values are Double, the other Int, the Int dates starting with 1523... can be decoded to Date with the appropriate date strategy:

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) }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...