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

标签 json swift api decoding

我正在快速使用 tfl 的 api,特别是线路状态 api,但我在解码嵌套对象 lineStatuses 内的 statusSeverityDescription 时遇到问题。理想情况下,我想一起检索该行的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
} 

关于json - 如何解码另一个数组中的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55847038/

相关文章:

ios - Swift:从 url 检索音频文件标记列表?

javascript - 无法在 ajax 调用中创建 window.location.reload()

javascript - "$"在 Visual Studio 中使用 jQuery 时未定义

ios - 具有自动布局的 UIPageViewController 在 vi​​ewDidAppear 之前不会更新子框架

swift - SwiftUI 中的圆角边框

javascript - Angularjs $http获取失败,但在 postman 和浏览器中请求成功

php - 使用 laravel 内置的 API 登录用户

api - 对实现 HATEOAS 的 rest API 的权限

java - jsonschema2pojo 不从 json 字符串生成 pojo 类

python - 如何处理json中的大括号转义