Swift Codable在嵌套字典上崩溃

时间:2018-10-17 21:26:33

标签: swift codable

我有一个复杂的JSON对象,看起来像这样(它被截断只是为了给出嵌套的想法:

{
    "absolute_magnitude_h" = "23.4";
    ...
    "close_approach_data" = (
                {
            "close_approach_date" = "1994-09-03";
            "epoch_date_close_approach" = 778575600000;
            "orbiting_body" = Earth;
    })
    "orbital_data" =     {
        "aphelion_distance" = "4.058036874987604";
       "orbit_class" = { 
            "orbit_class_type" = APO;
        }
    }

}

我的可编码对象看起来像这样:

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]()
    var orbitalData:NEOOrbitalData?

    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"
        case closeApproachData = "close_approach_data"
        case orbitalData = "orbital_data"
    }

}

struct NEOCloseApproachData:Codable {

    var closeApproachDate:String
    var orbitingBody:String
    var epochDateCloseApproach:Int

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

struct NEOOrbitalData: Codable {

    var aphelionDistance:Float

    enum CodingKeys: String, CodingKey {
        case aphelionDistance = "aphelion_distance"
    }

}

和我的代码:

do {

    let thisNEOObj = try? JSONDecoder().decode(NEOObj.self, from: jsonData)
    print(thisNEOObj)
   } catch {

   }

例如,我可以毫无问题地获得顶级键/值(absolute_magnitude_h),并且closeApproachData也将被填充。但是,如果我尝试检索orbital_data,则此NEOObj变为nil。我什至还没有尝试检索orbit_class。 :(

我要去哪里错了?

2 个答案:

答案 0 :(得分:0)

"4.058036874987604"String,不能在不进行自定义解码的情况下解码为var aphelionDistance: Float

答案 1 :(得分:0)

我建议您查看“使用面包”中的article,其中介绍了嵌套结构和处理自定义转换。您很可能需要创建一个自定义解码器来处理各种数据转换(尽管大多数将是样板)。您也可以跳过文章并查看code over on gist。我相信您的结构应在数据中包含所有JSON键。您可能还遇到问题,因为Float是“单精度浮点值类型”,而Double是“ A双精度浮点值类型”。尽管我没有仔细检查提供的数据是否会在您的设备上引起问题,但是切换到64位Double类型可能更简单。