我从API获取的数据返回一个单一对象,但是当有多个对象时,它会在同一个键中返回一个数组。使用当前的模型(struct),当出现数组时,解码会失败。
这些结果是随机排序的,意味着我无法知道何时将被提供对象或数组。
是否有一种方法可以创建一个考虑到这一点并且能够分配正确类型来转换值('String'或'[String]')的模型,以便解码可以顺利进行?
以下是返回对象的示例:
{
"firstFloor": {
"room": "Single Bed"
}
}
这是当数组返回时的示例(针对相同的键):
{
"firstFloor": {
"room": ["Double Bed", "Coffee Machine", "TV", "Tub"]
}
}
以下是一个可以作为模型解码上述两个示例的结构体示例:
struct Hotel: Codable {
let firstFloor: Room
struct Room: Codable {
var room: String // the type has to change to either array '[String]' or object 'String' depending on the returned results
}
}
这些结果是随机排列的,也就是说我不知道什么时候会收到一个对象或数组。
这里是完整的游乐场文件:
import Foundation
// JSON with a single object
let jsonObject = """
{
"firstFloor": {
"room": "Single Bed"
}
}
""".data(using: .utf8)!
// JSON with an array instead of a single object
let jsonArray = """
{
"firstFloor": {
"room": ["Double Bed", "Coffee Machine", "TV", "Tub"]
}
}
""".data(using: .utf8)!
// Models
struct Hotel: Codable {
let firstFloor: Room
struct Room: Codable {
var room: String // the type has to change to either array '[String]' or object 'String' depending on the results of the API
}
}
// Decoding
let decoder = JSONDecoder()
let hotel = try decoder.decode(Hotel.self, from: jsonObject) //
print(hotel)