Wrapping a reponse in another object using Moshi & Retrofit

Viewed 137

I'm using Moshi (with Retrofit) to map JSON to objects

I have a reponse like this:

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

And my retrofit interface looks like this:

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

So, the JSON that returns from the server, represents a User dto.

Here's the thing: I don't like how the server sometimes returns some objects directly as dto's and other times it doesn't.

So what i would like to do is to always have a Response object (in this case LoginResponse) that contains a dto object

How can i wrap the dto that is returned directly, in a response object? I was thinking that there's some kind of Root annotation, but unfortunatly it isn't that simple and i never used Moshi before

1 Answers

Seems to be working with this:

First i wrote an annotation:

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

Then i annotated my Api interface:

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

Finally i wrote a custom adapter:

class RootUserDTOAdapter {
    @RootUserDTO
    @FromJson
    fun fromJson(userDTO: UserDTO): LoginResponse {
        return LoginResponse(userDTO)
    }

    @ToJson
    fun toJson(@RootUserDTO loginResponse: LoginResponse): UserDTO {
        throw UnsupportedOperationException()
    }
}
Related