gpt4 book ai didi

ios - 无法从 weather-api 获取 json。 iOS

转载 作者:行者123 更新时间:2023-11-28 15:55:50 25 4
gpt4 key购买 nike

这是JSON文件

 {
"weather":[
{
"id":804,
"main":"Clouds",
"description":"overcast clouds",
"icon":"04d"
}
],
"main":{
"temp":273.15,
"pressure":1035,
"humidity":84,
"temp_min":273.15,
"temp_max":273.15
},

"name":"Wroclaw",

}

这是代码。

var cityName: String!
var degree: Int!
var someWeather: String!

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]


if let main = json["main"] as? [String : AnyObject] {
if let temp = main["temp"] as? Int {
self.degree = temp
}
}
if let city = json["name"] as? String {
self.cityName = city
}
}

if let weather = json["weather"] as? [String : AnyObject] {
if let someWeather = weather["main"] as? String {
self.weatherDescription = someWeather
}
}

labelWeather.text = self.weatherDescription

如何将json中天气的“main”或“description”的值保存到变量weatherDescription?我像在这段代码中那样尝试,但它没有显示任何内容。学位和城市名称工作正确并显示,但天气不起作用。

更新代码////////////////////////////////////////

  var  let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]


if let main = json["main"] as? [String : AnyObject] {
if let temp = main["temp"] as? Int {
self.degree = temp
}
if let pressuer = main["pressure"] as? Int {
self.cisnienie = pressuer
}
}

if let weather = json["weather"] as? [[String : Any]] {
for data in weather {
if let main = data["main"] as? String {
print(main)
}
}
}

if let nazwa = json["name"] as? String {
self.nazwaMiasta = nazwa
}

这里是所有的 JSON 文件:

{  
"coord":{
"lon":-0.13,
"lat":51.51
},
"weather":[
{
"id":800,
"main":"Clear",
"description":"clear sky",
"icon":"01d"
}
],
"base":"stations",
"main":{
"temp":279.07,
"pressure":1032,
"humidity":52,
"temp_min":278.15,
"temp_max":280.15
},
"visibility":10000,
"wind":{
"speed":7.2,
"deg":80
},
"clouds":{
"all":0
},
"dt":1484923800,
"sys":{
"type":1,
"id":5091,
"message":0.0087,
"country":"GB",
"sunrise":1484898825,
"sunset":1484929819
},
"id":2643743,
"name":"London",
"cod":200
}

最佳答案

“天气”是一个array 不是dictionary ..

if let weather = json["weather"] as? [[String : Any]] {
for data in weather{
if let main = data["main"] as? String{
print(main)
}
}
}

关于ios - 无法从 weather-api 获取 json。 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41761939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com