Home > Software design >  How to ignore some fields in API response - Retrofit @GET
How to ignore some fields in API response - Retrofit @GET

Time:01-17

I have a get API call. and the response is like this:

  {
      "id": "22222",
      "resourceUri": "ssss",
      "xxx": null,
      "xxx": [],
      "phone": "kkk",
      "email": "jjjjjj",
   }

out of all these fields, I only need the ID. SO, I've created a class like this:

data class ApiResponse(
    val id: String,
)

and api calls is like this:

suspend fun apiCall(@Header("Authorization") authorization : String) :Response<ApiResponse>

It doesn't work and it throws an error. What can I do?

CodePudding user response:

There seems to be nothing wrong for the implementation you provide. Your ApiResponse class can have less attributes than your response JSON.

If possible, please further provide the Exception you encounter.

I have a little example below for your reference:
Main.kt

fun main(args: Array<String>) {
  val retrofit = Retrofit.Builder().baseUrl("http://localhost")
    .addConverterFactory(GsonConverterFactory.create())
    .build()
  val retromock = Retromock.Builder().retrofit(retrofit).build()

  runBlocking {
    val service = retromock.create(TestCall::class.java)
    val response = service.apiCall()
    println(response.body())
  }
}

ApiResponse.kt

data class ApiResponse(
  val id: String,
  val name: String,
  val remark: String,
) {
  override fun toString(): String {
    return "ID: $id | Name: $name | remark: $remark"
  }
}

TestCall.kt

interface TestCall {
  @Mock
  @MockResponse(body = "{\"id\":\"1\", \"name\":\"Smith\", \"age\":30, \"score\":20, \"remark\":null}")
  @GET("/")
  suspend fun apiCall() : Response<ApiResponse>
}

And the output can be printed without errors:

ID: 1 | Name: Smith | remark: null

So in the above example, you can see that the returning JSON contains attributes like age, score, which are not included in ApiResponse. So you may have to check other configuration that causes the error.

CodePudding user response:

Yeah, Your API response is correct. you can create a response with the needed data only.

data class ApiResponse(
    val id: String,
)

your error may be something else please share your logcat error, it might be understood the error

  • Related