【问题标题】:Alamofire 5.5 responseDecodable on JSON arrayJSON数组上的Alamofire 5.5 responseDecodable
【发布时间】:2022-01-28 14:21:26
【问题描述】:

我正在尝试解码仅响应数组的 api 响应。我看到的所有使用 responseDecodable 的示例都是带有数据键或其他东西的字典。但是当我只是将 [Movie].self 作为解码器传递给我时:

failure(Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "name", intValue: nil), Swift.DecodingError.Context(codingPath: responseDecodable

我假设我做的不对,寻求帮助

获取/request

回应:

[{"id": 1, "name": "test"}]
struct Movie: Codable, Hashable {
    let id: Int
    let name: String
}
AF.request("http://localhost/request", parameters: parameters)
    .responseDecodable(of: [Movie].self) { response in
       debugPrint(response)
    }

【问题讨论】:

  • 它应该可以工作,但这真的是你的 JSON 吗?你能做print("Response String: \(String(data: response.data!, encoding:.utf8)") 并显示输出吗?
  • debugPrint(response) 应该包括接收到的 JSON 的完整输出,除非它非常大。在调试器中,我喜欢使用 po String(decoding: response.data!, as: UTF8.self) as NSString 来打印 JSON,因为它避免了 String 的转义。

标签: ios json swift alamofire


【解决方案1】:

根据错误,您的 JSON 没有返回 name 值,因此请检查它实际上是否应该是那个键,或者如果它不总是返回,则将该值标记为可选。 let name: String?

【讨论】:

    【解决方案2】:

    您需要先分配一个变量来接受 JSON 数据。从那里,您可以显示结果。举例说明:

           AF.request("http://localhost/request", parameters: parameters)
    .responseDecodable(of: [Movie].self) { response in
                    
            let myresult = try? JSON(data: response.data!)
    

    然后打印出来:

            debugPrint(myresult)
    

    如果您的 JSON 数据是可靠的,那么您在接收数据时应该没有问题。如果您的 JSON 是嵌套的,那么您可以向下钻取:

               let myresult = try? JSON(data: response.data!)
               let resultArray = myresult!["result"]
    

    等等。

    至于“KeyNotFound”错误......这是因为你所说的......它正在寻找字典键/值对。尝试上述示例后,应该可以解决此问题。此外,将“方法”放在 AF 请求中也是一种很好的做法。 :)

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 1970-01-01
      • 2021-03-13
      • 2017-01-15
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      相关资源
      最近更新 更多