Home > Back-end >  How to query filter json with Retrofit
How to query filter json with Retrofit

Time:11-04

I have api that return list of workers:

{
  "items": [
    {
      "id": "e0fceffa-cef3-45f7-97c6-6be2e3705927",
      "avatarUrl": "https://cdn.fakercloud.com/avatars/marrimo_128.jpg",
      "firstName": "Dee",
      "lastName": "Reichert",
      "userTag": "LK",
      "department": "back_office",
      "position": "Technician",
      "birthday": "2004-08-02",
      "phone": "802-623-1785"
    },
    {
      "id": "6712da93-2b1c-4ed3-a169-c69cf74c3291",
      "avatarUrl": "https://cdn.fakercloud.com/avatars/alterchuca_128.jpg",
      "firstName": "Kenton",
      "lastName": "Fritsch",
      "userTag": "AG",
      "department": "analytics",
      "position": "Orchestrator",
      "birthday": "1976-06-14",
      "phone": "651-313-1140"
    },
    ....
    ]
  }

I want to filter the response so that I only get information about a worker from a specific department. I tried to do it like this:

interface WorkersApi {
    @GET("users")
    suspend fun getWorkers(
            @Query("department") department: String
    ): Workers
}

But it return the same list without any filters. How can I filter the response so that I only get information about a worker from a specific department?

*Workers is just data class that hold only one field - list of items(workers)

CodePudding user response:

What you tried to do changes the request to the server. It sends the department as query parameter with the request. If the server doesn't support this parameter nothing happens. I don't know if you work together with the people controlling the backend but you could discuss with them if they could add functionality for filtered results.

If instead, you want to filter the results after getting the full list from the server simply apply a filter on the list that you got.

you could do this on your Workers object

val department = "example"
val filteredList = workersObject.items.filter {it.department == department}
  • Related