Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send an object array in a retrofit POST?

The Server is expecting something like this :

special_array = [{param1 = "string1", param2 = "string2"}, {param1 = "string3", param2 = "string4"}];

Do I need to make my own converter?

like image 757
sorinLates Avatar asked Sep 27 '22 08:09

sorinLates


People also ask

How do you send parameters in retrofit?

You can pass parameter by @QueryMap Retrofit uses annotations to translate defined keys and values into appropriate format. Using the @Query("key") String value annotation will add a query parameter with name key and the respective string value to the request url .


1 Answers

First create a callback interface like this and pass the whole Object class.

 @POST(URL)
 public void newObject(@Body YourObject object, Callback<Boolean> success);

Retrofit uses Gson to serialize and deserialize JSON by default. For Example, If your Object class looked like this:

public class YourObject {

@Expose
private String param1;
@Expose
private String param2;

/**
* 
* @return
* The param1
*/
public String getParam1() {
return param1;
}

/**
* 
* @param param1
* The param1
*/
public void setParam1(String param1) {
this.param1 = param1;
}

/**
* 
* @return
* The param2
*/
public String getParam2() {
return param2;
}

/**
* 
* @param param2
* The param2
*/
public void setParam2(String param2) {
this.param2 = param2;
}

}

Then Gson would automatically serialize into the following JSON,

[
    {
        "param1": "string1",
        "param2": "string2"
    },
    {
        "param1": "string3",
        "param2": "string4"
    }
]

And you are all done!

like image 185
Prokash Sarkar Avatar answered Oct 13 '22 02:10

Prokash Sarkar