gpt4 book ai didi

json - Swift JSON 解码器不同类型

转载 作者:行者123 更新时间:2023-11-30 10:29:16 28 4
gpt4 key购买 nike

我有这两个 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,但这是正确的方法吗?另外,如果这两个模型有很多属性,则组合结构会太大。

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)
}

关于json - Swift JSON 解码器不同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59461042/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com