[英]Swift JSON decode from URL
我的問題很簡單,但我找不到解決方案。 我知道有許多關於如何以其他方式做到這一點的教程,但我想保持簡單。
如果JSON html看起來像這樣,我知道如何獲取數據:
{"amount":"224.60","currency":"USD"}
但我不知道如何獲取數據,如果它看起來像這樣:
"main":{"temp":280.3,"pressure":1023,"humidity":75,"temp_min":280.15,"temp_max":280.37}
怎么說我需要從“主”獲得?
我的代碼看起來像這樣:
struct main: Decodable {
let humidity: String
}
let url = "http://api.openweathermap.org/data/2.5/weather?q=Vilnius,LTU&appid=8a3e3ef324cffc653933f3216efcf80f"
let urlObj = URL(string: url)
URLSession.shared.dataTask(with: urlObj!) {(data, response, error) in
do {
var airs = try JSONDecoder().decode(main.self, from: data!)
print(airs.humidity)
} catch {
print("error")
}
}.resume()
當我試圖獲得金額時,我的第一個例子工作得很好。 但它不適合我的第二個例子。
你可以試試
struct Root: Codable {
let main: Main
}
struct Main: Codable {
let temp: Double
let pressure, humidity: Int
let tempMin, tempMax: Double
enum CodingKeys: String, CodingKey {
case temp, pressure, humidity
case tempMin = "temp_min"
case tempMax = "temp_max"
}
}
var airs = try JSONDecoder().decode(Root.self, from: data!)
要么
do {
let con = try JSONSerialization.jsonObject(with:data, options: [:]) as! [String:Any]
let dataCC = con["main"] as! [String:Any]
let finData = try JSONSerialization.data(withJSONObject:dataCC, options: [:])
let userCon = try JSONDecoder().decode(Main.self, from:finData)
print(userCon)
}
catch {
print(error)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.