gpt4 book ai didi

json - Swift 解码 json 错误 : keyNotFound

转载 作者:行者123 更新时间:2023-11-30 11:26:39 25 4
gpt4 key购买 nike

{
"coord": {
"lon": -122.03,
"lat": 37.33
},
"weather": [
{
"id": 701,
"main": "Mist",
"description": "mist",
"icon": "50n"
}
],
"base": "stations",
"main": {
"temp": 287.01,
"pressure": 1012,
"humidity": 77,
"temp_min": 282.15,
"temp_max": 290.15
},
"visibility": 16093,
"wind": {
"speed": 1.5,
"deg": 290
},
"clouds": {
"all": 1
},
"dt": 1528023600,
"sys": {
"type": 1,
"id": 428,
"message": 0.0042,
"country": "US",
"sunrise": 1528030097,
"sunset": 1528082688
},
"id": 5341145,
"name": "Cupertino",
"cod": 200
}

我尝试使用以下代码将其解码为我的对象:

do {
let decoder = JSONDecoder()
let object = try decoder.decode(Object.self, from: data)
return object
} catch {
print("JSON Error: \(error)")
return Object(weather: Weather(), main: Main())
}

这是我的目标:

struct Object: Codable {
var weather: Weather
var main: Main
}

struct Weather: Codable {
var city = ""
var description = ""
var icon = ""

enum CodingKeys: String, CodingKey {
case city = "name"
case description = "main"
case icon
}
}

struct Main: Codable {
var temputure = ""

enum CodingKeys: String, CodingKey {
case temputure = "temp"
}
}

但是我收到错误:

JSON Error: typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "weather", intValue: nil)], debugDescription: "Expected to decode Dictionary but found an array instead.", underlyingError: nil))

我想知道如何解决这个问题。

最佳答案

CodingKeys(stringValue: "weather", intValue: nil)], debugDescription: "Expected to decode Dictionary but found an array instead

来自调试的此错误天气是一个数组[]而不是字典{}

在 Json 中,[] 是数组,{} 是字典

型号:

    struct Object: Codable {
let weather: [Weather]
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"
}
}
struct Weather: Codable {
let id: Int
let main, description, icon: String
}

使用它:

    do {
let decoder = JSONDecoder()
let object = try decoder.decode(Object.self, from: data)
return object
}
catch {
print("JSON Error: \(error)")
return Object(weather: Weather(), main: Main())
}

关于json - Swift 解码 json 错误 : keyNotFound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50666163/

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