【问题标题】:How I parse Following response using Codable?如何使用 Codable 解析以下响应?
【发布时间】:2019-10-18 13:07:37
【问题描述】:

如何使用Codable解析以下响应

{
    "Response": {
        "ResponseStatus": 1,`enter code here`
        "TraceId": "00125bf6-a416-4095-893c-05e05f8c7202",
        "Origin": "BOM",
        "Destination": "PNQ",
        "Results": [
                        [
                            {
                                "IsCouponAppilcable": true,
                                "IsGSTMandatory": false,
                                "AirlineRemark": "AI TEST.",
                            },
                            {
                                "IsCouponAppilcable": true,
                                "IsGSTMandatory": false,
                                "AirlineRemark": "AI TEST.",
                            }
                       ]
                ]
        }
}

我想使用Codable解析“结果”

我试过了,但卡住了如何解析“结果”

struct FlightResponceRequest : Codable {
    var Response : FlightResponce
}

struct FlightResponce : Codable {
    var ResponseStatus : Int?
    var Error : FlightError
    var TraceId : String?
    var Origin : String?
    var Destination : String?
    var Results : [FlightResult]?
}

struct FlightError : Codable {
    var ErrorCode : Int?
    var ErrorMessage : String?
} 

struct FlightResult : Codable {

}

【问题讨论】:

  • 请先尝试自己解决这个问题,如果您遇到困难,我们可以帮助您。
  • 将代码添加到您的问题中,而不是将其作为评论发布并解释问题所在,
  • 显示你使用JSONDecoder()的代码。显示我猜你发现的错误?像这样的代码最少:do { let result = try JSONDecoder().decode(FlightResponceRequest.self, from: json); print(result) } catch { print("Error: \(error)") } 和登录控制台...这将节省我们很多时间,这是你的职责,至少作为开发人员来捕获错误并阅读它们......
  • 嗨 Larme,请执行 {Flights.sharedInstance.flightObj = try JSONDecoder().decode(FlightResponceRequest.self, from: data) } 如果您检查我的结构,我在 FlightResult 中没有写任何东西?我的问题是我在 FlightResult 中写什么来解析“结果”
  • 在您的回复中,我没有看到 FlightError 字段,因此请尝试将其设为可选

标签: json swift codable


【解决方案1】:

你需要让它像响应一样,因为你在另一个数组中有一个数组。

var Results : [[FlightResult]]?

然后将键/值解析为您的 FlightResult 结构。

【讨论】:

    猜你喜欢
    • 2019-04-06
    • 2023-04-07
    • 2020-01-14
    • 1970-01-01
    • 2021-03-19
    • 2021-09-05
    • 1970-01-01
    • 2020-05-30
    • 2019-02-17
    相关资源
    最近更新 更多