【问题标题】:Retrofit2 Inconsistency Response from Server来自服务器的 Retrofit2 不一致响应
【发布时间】:2018-12-22 01:37:09
【问题描述】:

我是 Android 开发新手,正在学习如何使用 Retrofit,我很难处理来自服务器的不一致响应。

服务器会返回两种以上的响应。

我可以知道如何处理这种服务器响应吗? 我应该根据服务器响应创建不同的数据类来处理它吗?


服务器响应

结果 - 成功

{
    "status": true,
    "code": null,
    "result": {
        "id": 1,
        "name": "User",
        "email": "user@gmail.com",
        "created_at": "2018-07-12 15:25:42",
        "updated_at": "2018-07-12 15:25:42"
    }
}

结果 - 失败

{
    "status": false,
    "code": null,
    "result": "Server error."
}

结果 - 验证

{
    "status": true,
    "code": null,
    "result": {
        "email": [
            "The email field is required."
        ],
        "password": [
            "The password field is required."
        ]
    }
}

安卓

消息模型

import com.squareup.moshi.Json

data class Errors (
        @Json(name = "status") val status: Boolean?,
        @Json(name = "code") val code: Int?,
        @Json(name = "result") val message: Objects?
)

【问题讨论】:

  • 您可以使用适配器来转换您的响应并创建自定义对象
  • 最终,这是糟糕的 api 结构。但是是的,你需要一个适配器来转换
  • @crgarridos,你介意告诉我怎么做吗?
  • @ElliotM,我正在使用一个框架来创建 API,所以我没有太多的控制权。

标签: android kotlin retrofit moshi


【解决方案1】:

您可以多次使用“结果”键,具体取决于这样的响应状态

`       @Json(name = "status") val status: Boolean?,
        @Json(name = "code") val code: Int?,
        @Json(name = "result") val message: String?,
        @Json(name = "result") val result: ResultObject?,
        @Json(name = "result") val validation: HashMap<String,List<String>>?
`

并且取决于您的“状态”键,您可以通过设置条件从正确的“结果”键中获取正确的值。

【讨论】:

    猜你喜欢
    • 2011-01-26
    • 2023-04-11
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2013-01-02
    相关资源
    最近更新 更多