需要帮助解码包含数组的Json

时间:2019-04-03 20:01:15

标签: json swift decode

我需要执行以下操作: 定义两个Swift类以解码JSON字符串

解码JSON字符串以获取两个类的对象

这是我必须解码的JSON:

  

{“状态”:200,“假期”:[{“名称”:“感恩节”,“日期”:“ 2017-10-09”,“观察到”:“ 2017-10-09”,“公开” “:false}]}

我已经尝试创建两个类,并且在主类中调用该类时,我得到的一切都不是

class HolidayItems : Decodable {

    let name : String?
    let date : String?
    let observed: String?
    let `public` : Bool?


    private enum CodingKeys: String, CodingKey {

        case name
        case date
        case observed
        case `public`

    }

    required init(from decoder:Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        date = try container.decode(String.self, forKey: .date)
        observed = try container.decode(String.self, forKey: .observed)
        `public`  = try container.decode(Bool.self, forKey: .`public`)
    }

    } // HolidayItems

    class HolidayAPI: Decodable {

    let status: HolidayItems

    // let holiday :[HolidayItems]


    func getHolidayName() -> String {
        return status.name ?? "no advice, server problem"
    }
    func getAdviceNo() -> String {
        return status.date ?? ""
    }
    private enum CodingKeys: String, CodingKey {
        case status
        case holiday = "items"
    }

    required init(from decoder:Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        status = try container.decode(HolidayItems.self, forKey: .status)
      //  holiday = try container.decode(HolidayItems.self, forKey: .holiday)

    }
}

这是我应该得到的结果:

  

可选(“感恩节”)   可选(“ 2017-10-09”)

我一无所获

1 个答案:

答案 0 :(得分:1)

您的响应在根级别上是status类型为Int的对象,另一个对象是一个数组


注意

  • 您不必实施自定义CodingKey
  • 您不需要使用init的自定义Decoder
  • 您可以为模型准备struct
  • 您可以将HolidayItems重命名为Holiday

struct HolidayAPI: Decodable {
    let status: Int
    let holidays: [Holiday]
}

struct Holiday: Decodable {
    let name, date, observed: String
    let `public`: Bool
}

然后,当您需要获取某些节日用品时,只需获取holidays的某些元素

decodedResponse.holidays[0].name