数据I 'm getting from an API returns a single object but when there'是多个对象,它在同一个键中返回一个数组 . 使用我正在使用的当前模型(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)
1 回答
您可以使用Enum with Associated Values(在本例中为String和Array)来封装结果的歧义,例如: