Search code examples
androidkotlingsonretrofit

How to send custom array of objects with post body?


There is data classes PlaylistInsertOperation, TrackId and function insertTracks via Retrofit Interface.

data class PlaylistInsertOperation(
    val tracks: List<TrackId>,
)

data class TrackId(
    val id: String,
    val albumId: String
)

@FormUrlEncoded
@POST("/patch")
suspend fun insertTracks(
    @Field("diff") diff: List<PlaylistInsertOperation>
): PlaylistResponse

When I send request, field diff equals the next string

diff=PlaylistInsertOperation(tracks=[TrackId(id=39117009, albumId=5034819), TrackId(id=89341636, albumId=18635889)])

But need to such string

diff=[{"tracks":[{"id":"61081889","albumId":9499401}]}]

How to tell gson or retrofit parse models without data class name?


Solution

  • I create additional data class PlaylistDiffRequest with list of InsertTracksOperation. And override toString function that call gson.

    // Retrofit Interface
    @FormUrlEncoded
    @POST("/handlers/playlist-patch.jsx")
    suspend fun patchPlaylist(
        @Field("diff") diff: PlaylistDiffRequest,
    ): PlaylistResponse
    
    // Models
    data class InsertTracksOperation(
        val tracks: List<TrackId>,
    )
    
    data class PlaylistDiffRequest(val diff: List<Any>) {
        override fun toString(): String = Gson().toJson(diff)
    }
    

    In this case output field will be as I need

    diff=[{"tracks":[{"albumId":"6250697","id":"35629702"}]}]