gpt4 book ai didi

ios - 获取数组中字典的值

转载 作者:行者123 更新时间:2023-11-28 13:44:00 25 4
gpt4 key购买 nike

我正在尝试从数组中的字典中获取一些值,但我不知道该怎么做。我能够从字典和数组中获取东西,但不能将它们结合起来。如果有帮助的话,我正在使用 openweathermap hourly api。

我尝试将我做过的两种不同方法结合起来,但没有奏效。这是我尝试过的:

struct HourlyWeatherAPI: Decoder
{
let main: Main
let wind: Wind
struct Main: Decodable
{
let temp: Double
}
struct Wind: Decodable
{
let speed, deg: Double
}
}

那个 -^ 在我的代码的顶部,然后这是很久以后

if let tempJson = jsonObject["list"] as? [[String:AnyObject]]
{
for eachTemp in tempJson
{
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder.decode(HourlyWeatherAPI.Main.self, from: data!)
print(result.temp)
}
}

这是 API 中的一些内容,只是第一个条目。我正在尝试获取 main 中的内容:

{
"cod": "200",
"message": 0.0197,
"cnt": 96,
"list": [
{
"dt": 1555196400,
"main": {
"temp": 282.26,
"temp_min": 281.409,
"temp_max": 282.26,
"pressure": 1018.06,
"sea_level": 1018.06,
"grnd_level": 985.672,
"humidity": 56,
"temp_kf": 0.85
},
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04d"
}
],
"clouds": {
"all": 100
},
"wind": {
"speed": 3.99,
"deg": 313.922
},
"sys": {
"pod": "d"
},
"dt_txt": "2019-04-13 23:00:00"
},

最佳答案

您希望您的数据结构与您接收到的 JSON 相匹配,从根级对象开始。然后您可以解码根对象并访问包含的数据结构。

struct Root: Decodable {
let list:[HourlyWeatherAPI]
}

struct HourlyWeatherAPI: Decodable {
let main: Main
let wind: Wind
}

struct Main: Decodable {
let temp: Double
}

struct Wind: Decodable {
let speed, deg: Double
}

/*
* decode your JSON as before, but use the new Root object as the type. You
* can then access the hourly weather data from the list property
*/
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder.decode(Root.self, from: data!)
let hourlyWeatherList = result.list
let firstWeatherItem = hourlyWeatherList[0]
let temp = firstWeatherItem.main.temp

关于ios - 获取数组中字典的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55670611/

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