【问题标题】:Need help decoding Json that contains an array需要帮助解码包含数组的 Json
【发布时间】:2019-04-03 20:01:14
【问题描述】:

我需要做以下事情: 定义两个 Swift 类来解码 JSON 字符串

解码JSON字符串得到两个类的对象

这是我必须解码的 JSON:

{“status”:200,"holidays":[{"name":"Thanksgiving","date":"2017-10-09","observed":"2017-10-09","public ":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”)

我一无所获

【问题讨论】:

    标签: json swift decode


    【解决方案1】:

    您的响应是在根级别,只是具有 Int 类型的 status 的对象和另一个对象的一个​​数组


    注意

    • 您不必实现您的自定义CodingKey
    • 你不需要自定义initDecoder
    • 您的模型可以使用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
    

    【讨论】:

    • 感谢您的回复。我需要上课,这就是我在主类 self.holiday = try JSONDecoder().decode(HolidayAPI.self, from: self.dataStore as Data) self.holidayTextView.text = self.holiday? 中的称呼方式。 getHolidayName() 打印(self.holidayTextView.text)
    • @newtoSwift 但你不能像处理单个对象那样处理你的响应,你会收到对象数组
    • 成功了,谢谢。我正在研究一个 JSON 中没有数组的示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多