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

问题描述 投票:0回答:1

我正在玩swfl中的tfl的api,特别是行状态api但是我在解码嵌套对象statusSeverityDescription中的lineStatuses时遇到了麻烦。理想情况下,我想一起检索线的namestatusSeverityDescription

我能够从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)
json swift api decoding
1个回答
0
投票

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

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

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

struct Status : Decodable {

    let statusSeverityDescription : String
} 
© www.soinside.com 2019 - 2024. All rights reserved.