问题描述
我目前正在使用处理公交车预测的API。有一个有趣的关于JSON的怪癖,它返回用于某个停靠点的预测。当有多个停止预测时,JSON看起来像这样:
I currently am working with an API that deals with bus predictions. There is an interesting quirk with the JSON that is returned for the predictions of a certain stop. When there are multiple predictions for a stop, the JSON looks something like this:
...
"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改为:
However, when there is only one prediction for a stop, the JSON looks like this instead:
...
"direction": {
"prediction":
{
"affectedByLayover": "true",
"block": "241",
"dirTag": "loop",
"epochTime": "1571785998536",
"isDeparture": "false",
"minutes": "20",
"seconds": "1208",
"tripTag": "121",
"vehicle": "1698"
}
"title": "Loop"
}
...
请注意,预测不再位于数组中-这是我认为使用a时事情变得越来越复杂的地方Swift Codable类型以解码JSON。对于方向和预测,我的模型看起来像这样
Notice that the "prediction" is no longer inside an array -- this is where I believe things are getting complicated when using a Swift Codable type to decode the JSON. My model looks like this for the "direction" and "prediction"
struct BTDirection: Codable {
let title: String!
let stopTitle: String!
let prediction: [BTPrediction]!
}
struct BTPrediction: Codable {
let minutes: String!
let vehicle: String!
}
基本上,发生的是预测$ c
BTDirection
中的$ c>正在寻找BTPrediction数组,但是在上述第二种情况下,它不是数组,因此解码失败。如何使我的模型更灵活以容纳数组或单个对象?理想情况下,在第二种情况下,预测
仍将是单个 BTDirection
的数组。
Basically what is happening is prediction
in BTDirection
is looking for an Array of BTPrediction, however in the 2nd case above, this wouldn't be an Array so the decoding fails. How can I make my models more flexible to accommodate both an array or a single object? Ideally, in the 2nd case prediction
would still be an array of a single BTDirection
. Any help on this would be much appreciated.
推荐答案
您可以尝试
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]
}
}
}
这篇关于如何使Swift Codable类型更通用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!