我正在尝试解析以下json架构,海报可能为空,也可能不为空
{
"poster": {},
"recommends": []
}
我的可解码课程如下:
public struct RecommendedList: Decodable {
public let poster: Poster?
public let recommends: [Recommend]
}
public struct Poster: Decodable {
public let backgroundImage: URL
public let topImage: URL
public let windowImage: URL
public let windowSkinImagePath: URL
public let deeplink: URL
public init(from decoder: Decoder) throws {
// I want a failable intializer not one that throws
}
}
我的问题是如何制作海报可选?我的想法是我需要一个可用的初始化程序,但可解码需要一个抛出的初始化。
答案 0 :(得分:1)
所以看起来我需要添加一个尝试?在推荐列表init(来自解码器:)
public struct RecommendedList: Decodable {
public let poster: Poster?
public let recommends: [Recommend]
enum CodingKeys: String, CodingKey {
case poster
case recommends
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
poster = try? container.decode(Poster.self, forKey: .poster)
recommends = try container.decode([Recommend].self, forKey: .recommends)
}
}