【问题标题】:Wrapping a reponse in another object using Moshi & Retrofit使用 Moshi 和 Retrofit 将响应包装在另一个对象中
【发布时间】:2021-05-24 21:35:44
【问题描述】:

我正在使用 Moshi(带有 Retrofit)将 JSON 映射到对象

我有这样的回应:

{
   "email:"test@gmail.com"
   "name":"test"
}

而我的改造界面是这样的:

@POST("login")
suspend fun login(@Body request: LoginRequest): UserDTO

因此,从服务器返回的 JSON 代表一个用户 dto。

事情是这样的:我不喜欢服务器有时会直接将某些对象作为 dto 返回,而有时则不会。

所以我想做的是始终拥有一个包含 dto 对象的 Response 对象(在本例中为 LoginResponse)

如何将直接返回的 dto 包装在响应对象中?我在想有某种 Root 注释,但不幸的是它不是那么简单,我之前从未使用过 Moshi

【问题讨论】:

    标签: android retrofit moshi


    【解决方案1】:

    似乎正在处理这个问题:

    首先我写了一个注释:

    @Retention(AnnotationRetention.RUNTIME)
    @JsonQualifier
    annotation class RootUserDTO
    

    然后我注释了我的Api接口:

    @POST("login")
    @RootUserDTO
    suspend fun login(@Body request: LoginRequest): LoginResponse
    

    最后我写了一个自定义适配器:

    class RootUserDTOAdapter {
        @RootUserDTO
        @FromJson
        fun fromJson(userDTO: UserDTO): LoginResponse {
            return LoginResponse(userDTO)
        }
    
        @ToJson
        fun toJson(@RootUserDTO loginResponse: LoginResponse): UserDTO {
            throw UnsupportedOperationException()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2020-11-19
      • 2018-07-15
      • 1970-01-01
      • 2018-07-26
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      相关资源
      最近更新 更多