androidkotlininterfaceretrofitjsonobjectrequest

How do i get a Retrofit Response of some particular Objects and sort them?


i am using Retrofit and i am getting the response without any problems, i am fetching the data and everything works well, but i only need to get the items with projectType == "FOLDER", discarding the projectType == "PROJECT" ones.

How can i manage this? I also want to sort them based on creation date.

interface ApiInterface {


@GET("projects")
fun getData(@Header("secretKey") apiKey : String): Call<ProjectList>}

Sample output:

{
"projects": [
    {
        "id": "00001",
        "creation": 1611162020,
        "projectType": "FOLDER",
        "name": "3 - Aufträge",        
        "archived": false
    },
    {
        "id": "00002",
        "creation": 1611158408,          
        "projectType": "PROJECT",
        "name": "Unter",
        "archived": false
    },
    {
        "creation": 122234,
        "name": "4 - Aus",
        "id": "00003",           
        "projectType": "FOLDER",
        "archived": false
    }]}

Solution

  • You can easily filter your items using filter function as shown below

    pList.projects.filter{ it.projectType == "FOLDER" }
    

    Also if you want to sort your items based on a property, you can use sortedBy and sortedByDescending like below

    val ans = pList.projects
        .filter{ it.projectType == "FOLDER" }
        .sortedBy { it.position.creation }
    

    And for reversed order

    val ans = pList.projects
        .filter{ it.projectType == "FOLDER" }
        .sortedByDescending { it.position.creation }