我得到了一些类似这样的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
需要一个
case closeApproachData = "close_approach_data"
closeApproachData
需要一个自定义解码器来处理NEOCloseApproachData
和closeApproachDate
的日期。由于JSON的格式各不相同(分别为String和Int),因此不能在epochDateCloseApproach
上使用,因为它将应用于所有日期。关于swift - Swift Codable:嵌套字典未读取,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52861083/