如何解码另一个数组中的 JSON 数组

How to decode an array of JSON inside another array

我正在 swift 中使用 tfl 的 api,特别是行状态 api,但我在解码嵌套对象内的 statusSeverityDescription 时遇到问题lineStatuses。理想情况下,我想一起检索行的 namestatusSeverityDescription

我能够正确解码来自 JSON 的行的 name,所以我确定问题只是数组的解码错误。

这里是 api 的 url 问题: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)

lineStatuses 是一个数组,所以在 Line 中更改它的声明如下,

struct Line : Decodable {
    let name : String
    let lineStatuses : [Status]
}

你也可以在 Status 中省略 init 声明,如

struct Status : Decodable {

    let statusSeverityDescription : String
}