我目前正在使用处理公交车预测的 API。为某个站点的预测返回的 JSON 有一个有趣的怪癖。当有多个停止预测时,JSON 看起来像这样:
...
"direction": {
"prediction": [
{
"affectedByLayover": "true",
"block": "241",
"dirTag": "loop",
"epochTime": "1571785998536",
"isDeparture": "false",
"minutes": "20",
"seconds": "1208",
"tripTag": "121",
"vehicle": "1698"
},
{
"affectedByLayover": "true",
"block": "241",
"dirTag": "loop",
"epochTime": "1571787798536",
"isDeparture": "false",
"minutes": "50",
"seconds": "3008",
"tripTag": "122",
"vehicle": "1698"
},
{
"affectedByLayover": "true",
"block": "241",
"dirTag": "loop",
"epochTime": "1571789598536",
"isDeparture": "false",
"minutes": "80",
"seconds": "4808",
"tripTag": "123",
"vehicle": "1698"
}
],
"title": "Loop"
}
...
但是,当只有一个停止预测时,JSON 看起来像这样:
...
"direction": {
"prediction":
{
"affectedByLayover": "true",
"block": "241",
"dirTag": "loop",
"epochTime": "1571785998536",
"isDeparture": "false",
"minutes": "20",
"seconds": "1208",
"tripTag": "121",
"vehicle": "1698"
}
"title": "Loop"
}
...
请注意,“预测”不再位于数组内——这是我认为使用 Swift Codable 类型解码 JSON 时事情变得复杂的地方。对于“方向”和“预测”,我的模型看起来像这样
struct BTDirection: Codable {
let title: String!
let stopTitle: String!
let prediction: [BTPrediction]!
}
struct BTPrediction: Codable {
let minutes: String!
let vehicle: String!
}
基本上发生的事情是 BTDirection
中的 prediction
正在寻找一个 BTPrediction 数组,但是在上面的第二种情况下,这不是一个数组,因此解码失败。如何使我的模型更灵活以适应数组或单个对象?理想情况下,在第二种情况下,prediction
仍然是单个 BTDirection
的数组。对此的任何帮助将不胜感激。
最佳答案
你可以试试
struct BTDirection:Codable {
let title,stopTitle: String
let prediction: [BTPrediction]
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
title = try container.decode(String.self, forKey: .title)
stopTitle = try container.decode(String.self, forKey: .stopTitle)
do {
let res = try container.decode([BTPrediction].self, forKey: .prediction)
prediction = res
}
catch {
let res = try container.decode(BTPrediction.self, forKey: .prediction)
prediction = [res]
}
}
}
关于ios - 如何使 Swift Codable 类型更加通用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58513344/