【发布时间】:2018-02-12 04:55:32
【问题描述】:
我从 API 获取的数据返回单个对象,但是当有多个对象时,它会返回同一个键中的数组。使用我正在使用的当前模型(结构),当数组出现时解码失败。
这些结果是随机排序的,这意味着我不知道什么时候会为我提供对象或数组。
有没有办法创建一个考虑到这一事实的模型,并且可以分配正确的类型来强制转换值('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)
【问题讨论】:
标签: arrays json swift swift4 codable