【问题标题】:Handling two different Retrofit responses for success and error in Kotlin在 Kotlin 中为成功和错误处理两种不同的改造响应
【发布时间】:2021-12-28 14:30:37
【问题描述】:

我正在 Kotlin 中构建一个 android 应用程序,响应以两种不同的结构来表示成功和错误。我的问题是,我可以将这两个响应组合在一起并创建一个数据类,还是应该为此创建一个密封类? 成功响应:

{
    "access_token": "xxxxxxxxxxxxxxxxxxxx",
    "token_type": "bearer"
}

错误响应:

{
    "detail": [
        {
            "loc": [
                "body"
            ],
            "msg": "Invalid credentials",
            "type": "invalid-credentials"
        }
    ]
}

那么我可以在单个数据类中这样写,还是使用密封类?

data class Auth (
   val access_token: String,
   val token_type: String,
   val details: Details
)

【问题讨论】:

    标签: android api kotlin retrofit


    【解决方案1】:

    是的,请尝试将所有数据合并到一个数据类中。只需将所有变量设为可选即可。

    data class Auth (
       val access_token: String?,
       val token_type: String?,
       val detail: List<Detail>?
    )
    

    编辑:关于如何访问嵌套数据。很简单。

    data class Detail ( 
      val loc: List<String>,
      val msg: String,
      val type: String
    )
    

    然后,当发生错误时,您可以使用 val msg = auth.detail?.msg 之类的内容访问数据

    【讨论】:

    • 所以你认为根据成功和错误,数据类不需要密封类,它会一样工作吗?
    • 没必要。对于您提供的示例,使用密封类会过度设计。
    • 但是我应该如何访问属于 Details 类的观察方法 msg 或 loc 或类型?
    • 我更新了我的答案。让我知道这是否有帮助。
    • 我尝试了访问 msg、loc 或 type 的方法,但我无法访问它我不知道为什么
    猜你喜欢
    • 1970-01-01
    • 2015-10-10
    • 2021-07-20
    • 2018-12-16
    • 1970-01-01
    • 2020-09-15
    • 2021-12-21
    • 2018-07-07
    • 1970-01-01
    相关资源
    最近更新 更多