A. Cedano
A. Cedano

Reputation: 965

How can I convert an API response to objects of any type in Kotlin using Retrofit?

I'm working on an application with about 100 different tables in the room database.

This application must periodically search the server for possible changes in any of those 100 tables from a given date. To do this, a request is launched to the API using Retrofit.

My idea is to receive that response and map it to an object called Crud, and then do the corresponding operation with each table, regardless of what tables there are at that moment (create, read, update, delete), using for them an interface BaseDao. The response could contain data for any of the 100 tables.

This is an example response:

{
  "haveData":true,
  "crud":[
    {
      "LHPsalmodyJoin":{
        "create":[
          {
            "groupID":100030203,
            "theType":1,
            "crud":"c"
          },
          {
            "groupID":102030206,
            "theType":0,
            "crud":"c"
          }
        ],
        "update":[
          {
            "groupID":100030203,
            "theType":1,
            "crud":"c"
          }
        ]
      },
      "LHPatristic":{
        "update":[
          {
            "groupID":108002301,
            "crud":"u"
          }
        ],
        "delete":[
          {
            "groupID":108001801,
            "crud":"d"
          },
          {
            "groupID":108001901,
            "crud":"d"
          }
        ]
      }
    }
  ]
}

As you can see:

This is the Crud class that this API response maps to:

class Crud {
    val lastUpdate: String = ""
    val haveData = false
    val crud: List<Any> = emptyList()

    //Loop in the crud property 
    //calling the corresponding BaseDao method for each object
}

This is BaseDao:

interface BaseDao<T> {

    @Insert
    fun insert(obj: T)

    @Insert
    fun insert(vararg obj: T)

    @Update
    fun update(obj: T)

    @Insert
    fun update(vararg obj: T)

    @Delete
    fun delete(obj: T)

    @Insert
    fun delete(vararg obj: T)
}

The problem

My problem is that the response does not map to objects of any type.

Instead of mapping to objects of type LHPsalmodyJoin and LHPatristic for this case, it is being mapped to aLinkedTreeMap object, as you can see in this inspector image:

enter image description here

How can I map this response to their respective objects, to pass it to the corresponding BaseDao method?

Upvotes: 0

Views: 298

Answers (0)

Related Questions