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?
CodePudding user response:
You cannot pass JSON object in @FormUrlEncoded. You can use @Body annotation to pass JSON
@POST("/patch")
suspend fun insertTracks(
@Body body: PlaylistInsertOperationRequest
): PlaylistResponse
Create another class for request
data class PlaylistInsertOperationRequest(
@SerializedName("diff") val diff : List<PlaylistInsertOperation>
)
CodePudding user response:
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"}]}]