Home > Software design >  Parse model from data object
Parse model from data object

Time:12-24

My API returns a response that looks like this:

{
    status: number,
    message?: string,
    data?: T,
}

So in a retrofit service I have to wrap all return values in this response class:

data class Response<T>(val status: Int, val message: String?, val data: T?)

interface MyService {
    @GET("user")
    suspend fun getUser(id: String): Response<User>
}

Now the question: How can make it return a class without wrapping a return value?

suspend fun getUser(id: String): User

CodePudding user response:

The way you are making the interface you'll have to make multiple functions return multiple return objects. Try Making a Generic Response interface and then Handle the response in your code. Make your interface like this :

@GET
suspend fun getUser(@Url endpoint: String,id: String): Call<ResponseBody>

Then in your Response Function Use it like :

override fun onResponse(call : Call<ResponseBody>,response: Response<ResponseBody>) {
        //Parse your object here
        String responseBody = response.body().string();
        JSONObject json = new JSONObject(responseBody);
        val responseObject : User = Gson().fromJson(
                    json.optJSONObject("data")?.toString(),
                    User::class.java)
    }

make sure to implement Gson in your app gradle.

CodePudding user response:

You can adapt return types using Retrofit's CallAdapter and CallAdapter.Factory. Knowing this should help you find some code examples online, which you can adapt to your specific use case.

  • Related