我需要执行以下操作: 定义两个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”)
我一无所获
答案 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