gpt4 book ai didi

swift 可编码 :Nested Dictionary not being read

转载 作者:行者123 更新时间:2023-11-28 10:37:10 26 4
gpt4 key购买 nike

我得到了一些像这样的 json(这是伪造的,并不是所有的键都在这里):

{
"absolute_magnitude_h" = "23.4";
...
"close_approach_data" = (
{
"close_approach_date" = "1994-09-03";
"epoch_date_close_approach" = 778575600000;
"orbiting_body" = Earth;
}

我有一个具有这个结构的对象:

struct NEOObj:Codable {

var absoluteMagnitudeH:Float
var designation:String
var isPotentiallyHazardousAsteroid:Bool
var isSentryObject:Bool
var name:String
var nasaJPLURL:String
var neoReferenceID:String
var closeApproachData:[NEOCloseApproachData] = [NEOCloseApproachData]()

private enum CodingKeys: String, CodingKey {
case absoluteMagnitudeH = "absolute_magnitude_h"
case designation = "designation"
case isPotentiallyHazardousAsteroid = "is_potentially_hazardous_asteroid"
case isSentryObject = "is_sentry_object"
case name = "name"
case nasaJPLURL = "nasa_jpl_url"
case neoReferenceID = "neo_reference_id"
}

enum CloseApproachCodingKeys: String, CodingKey {
case closeApproachDate = "close_approach_date"
case epochDateCloseApproach = "epoch_date_close_approach"
case orbitingBody = "orbiting_body"
}

struct NEOCloseApproachData:Codable {

var closeApproachDate:Date
var epochDateCloseApproach:Date
var orbitingBody:String

enum CodingKeys: String, CodingKey {
case closeApproachDate = "close_approach_date"
case epochDateCloseApproach = "epoch_date_close_approach"
case orbitingBody = "orbiting_body"
}
}

在我的文件中我有这段代码:

if let arrNEOs = dictJSON["near_earth_objects"] as? Array<Any> {

for thisNEODict in arrNEOs {

do {
let jsonData = try JSONSerialization.data(withJSONObject: thisNEODict, options: .prettyPrinted)
let thisNEOObj = try? JSONDecoder().decode(NEOObj.self, from: jsonData)
print(thisNEOObj!.closeApproachData)
} catch {

}
}

}

但是 closeApproachData 永远不会被填充。我做错了什么?

最佳答案

要使其正常工作,需要更改多项内容。


closeApproachData 应该是 [NEOCloseApproachData] 类型。您没有在代码中包含 CloseApproachCodingKeys,但它可能不正确。


NEOObj.CodingKeys 需要有一个 closeApproachData 的案例,看起来像

case closeApproachData = "close_approach_data"

NEOCloseApproachData 需要一个自定义解码器来处理 closeApproachDateepochDateCloseApproach 的日期。由于 JSON 具有不同的格式(分别为 String 和 Int),您不能在 JSONDecoder.dateDecodingStrategy 上使用,因为它将应用于所有日期。

关于 swift 可编码 :Nested Dictionary not being read,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52861083/

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