提问人:SamusesApple 提问时间:3/26/2023 最后编辑:SamusesApple 更新时间:3/26/2023 访问量:72
从“aqicn.org”解码 JSON 数据时出错 [已关闭]
Error when decoding a JSON data from "aqicn.org" [closed]
问:
我是 swift 编程的新手,我陷入了这个问题,解析我从“https://aqicn.org/api/”获得的 JSON 数据。
因为,我想要的数据只是一个“aqi”,所以我在下面做了一个超级简单的模型来解析JSON数据。 (另请参阅下面所附截图)
struct Dust: Codable {
let data: DataClass
}
struct DataClass: Codable {
let aqi: Int
}
另外,这是我收到的错误消息。
keyNotFound(CodingKeys(stringValue: "aqi", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"aqi\", intValue: nil) (\"aqi\").", underlyingError: nil))
似乎我制作的模型是错误的,但是,我不确定问题出在哪里。 我确实将 aqi 更改为 String 并重试,但错误仍然出现。
这是解码功能,以防万一......
func parseDustJSON(_ dustData: Data) -> Int? {
print(#function)
do {
let decodedDustData = try JSONDecoder().decode(DataClass.self, from: dustData)
let dustData = decodedDustData
return dustData.aqi
} catch {
print(error)
return nil
}
}
}
如果有人能帮助我,我将不胜感激。
答:
1赞
HangarRash
3/26/2023
#1
你需要通过,而不是.Dust.self
DataClass.self
let decodedDustData = try JSONDecoder().decode(Dust.self, from: dustData)
return decodedDustData.data.aqi
评论
0赞
SamusesApple
3/26/2023
嗨,我之前也试过..它说“typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: ”data“, intValue: nil)], debugDescription: ”Expected to decode Dictionary<String, Any> but found a string/data instead.“, underlyingError: nil))”
1赞
HangarRash
3/26/2023
那么你的问题就不在于JSON的解码了。你的问题是你没有得到想要的JSON。
1赞
SamusesApple
3/26/2023
多谢!我只是仔细检查了我的请求,我写的城市参数是错误的......希望你有美好的一天!
评论