我正在快速使用tfl的api,特别是线路状态api,但是在解码嵌套对象statusSeverityDescription
中的lineStatuses
时遇到了麻烦。理想情况下,我想同时检索该行的name
和statusSeverityDescription
。
我能够从JSON正确解码行的name
,所以我确定问题只是数组的解码错误。
这是有问题的api的网址:https://api.tfl.gov.uk/line/mode/tube/status?detail=true
struct Line : Decodable {
let name : String
let lineStatuses : Status
}
struct Status : Decodable {
let statusSeverityDescription : String
private enum CodingKeys : String, CodingKey {
case statusSeverityDescription = "statusSeverityDescription"
}
init(from decoder : Decoder) throws {
if let container = try? decoder.container(keyedBy: CodingKeys.self) {
self.statusSeverityDescription = try! container.decode(String.self, forKey: .statusSeverityDescription)
} else {
let context = DecodingError.Context.init(codingPath: decoder.codingPath, debugDescription: "Unable to decode statuses!")
throw DecodingError.dataCorrupted(context)
}
}
//this is in the UrlSession function
if let journey = try? JSONDecoder().decode([Line].self, from: data)
print(journey)
答案 0 :(得分:0)
lineStatuses
是一个数组,因此如下所述在Line
中更改其声明,
struct Line : Decodable {
let name : String
let lineStatuses : [Status]
}
您还可以在init
中省略Status
声明,
struct Status : Decodable {
let statusSeverityDescription : String
}