json - Swift JSON解码器不同类型
问题描述
我有这两个 JSON 对象
[
{"name": "Popular Movies",
"description": "Basic movie description",
"type": "movies",
"items": [ { "id": 15, "name": "Sample movie", "movieSPT": ""}]
},
{"name": "Popular TV Shows",
"description": "Basic shows description",
"type": "tvshows",
"items": [ { "id": 15, "name": "Sample show", "showSPT": ""}]
}
]
然后我为节目和电影创建了两个可解码结构:
struct Movie: Decodable {
let id: Int
let name: String
let movieSPT: String
}
struct TVShow: Decodable {
let id: Int
let name: String
let showSPT: String
}
那么,当我为主要响应创建对象时,创建项目数组的最佳方法是什么取决于类型值?我知道我可以为某些独特的结构创建带有可选属性的 showSPT 和 movieSPT,但这是正确的方法吗?另外,如果这两个模型有很多属性,combine struct 就会太大。
struct Blocks : Decodable {
let name: String
let description: String
let type: String
let items: [Movie] or [Show] based on type????
}
解决方案
有几个解决方案。其中之一是具有关联类型的枚举
let jsonString = """
[{"name": "Popular Movies", "description": "Basic movie description", "type": "movies",
"items": [ { "id": 15, "name": "Sample movie", "movieSPT": ""}]
},
{"name": "Popular TV Shows", "description": "Basic shows description", "type": "tvshows",
"items": [ { "id": 15, "name": "Sample show", "showSPT": ""}]
}
]
"""
let data = Data(jsonString.utf8)
struct Movie : Decodable {
let id: Int
let name, movieSPT: String
}
struct TVShow : Decodable {
let id: Int
let name, showSPT: String
}
enum MediaType {
case movie([Movie]), tvShow([TVShow])
}
struct Media : Decodable {
let name : String
let description : String
let items : MediaType
private enum CodingKeys : String, CodingKey { case name, description, type, items }
init(from decoder : Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.description = try container.decode(String.self, forKey: .description)
let type = try container.decode(String.self, forKey: .type)
if type == "movies" {
let movieData = try container.decode([Movie].self, forKey: .items)
items = .movie(movieData)
} else { // add better error handling
let showData = try container.decode([TVShow].self, forKey: .items)
items = .tvShow(showData)
}
}
}
do {
let result = try JSONDecoder().decode([Media].self, from: data)
print(result)
} catch {
print(error)
}