RaZoDiuM
RaZoDiuM

Reputation: 223

How to include "param" name in JSON @Body Retrofit Android

I need to call a service from Android. I tested the service with Postman and it works, but the services receives one parameter named "parametros", is a ArrayList in JSON format, it looks like this enter image description here

the right format is

{
    "parametros": [
        {
            "Nombre": "@@IdCliente",
            "Valor": "1"
        }
    ]
}

it's with the param name "parametros" included. In postman it works fine.

But in Android I have:

interface APIService {

    @POST("/getMovimientos")
    fun getMovimientos(@Body parametros: List<APIParameter>): Call<BalanceVO>
}

and my request looks like this:

D/OkHttp: --> POST https://xxxxxxx/getMovimientos
    Content-Type: application/json; charset=UTF-8
    Content-Length: 38
D/OkHttp: [{"Nombre":"@@IdCliente","Valor":"1"}]
    --> END POST (38-byte body)

The parameter

[{"Nombre":"@@IdCliente","Valor":"1"}]

should be

"parametros":[{"Nombre":"@@IdCliente","Valor":"1"}]

How can I configure my app to put this param name?

Upvotes: 1

Views: 903

Answers (2)

All Іѕ Vаиітy
All Іѕ Vаиітy

Reputation: 26452

Construct your body as an object of a data class as below

data class APIRequestPayload (
    val parametros: List<APIParameter>
)

data class APIParameter (
    val Nombre: String,
    val Valor: String
)

then use it as the below on service

fun getMovimientos(@Body parametros: APIRequestPayload): Call<BalanceVO>

To use it, pass the body as an obj,

service.getSaldo(parametros=APIRequestPayload(parametros=List<APIParameter>)).enqueue()

Still naming the val Nombre is not conventional, you may annotate with @SerializedName("Nombre") val nombre to stick with variable naming conventions if using GSON

Upvotes: 1

Arpan Sarkar
Arpan Sarkar

Reputation: 2406

Create a data class like this and assign list to it and pass it as body

data class ParametrosBody(val parametros: List<APIParameter>)
val parametros = ...//your list
val body = ParametrosBody(parametros)
interface APIService {

    @POST("/getMovimientos")
    fun getSaldo(@Body parametros: ParametrosBody): Call<BalanceVO>
}

Upvotes: 1

Related Questions