Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2 send an empty array

Tags:

java

retrofit2

I'm sending an array of integers to the backend via this Retrofit interface:

@PATCH("save/ids")
@FormUrlEncoded
Call<Output> saveIds(@Field("ids[]") List<Integer> ids);

Now this works when I have an ArrayList with some items. But to reset all the ids the servers wants an empty array called ids. When I send an empty array, Retrofit doesn't send the array - it just drops the parameter.

I create my ArrayList as follows:

List<Integer> ids = new ArrayList<>();
for (FooObjects object : listOfIds) {
    if (object.isEnabled()) {
        ids.add(object.getId());
    }
}

How can I send an empty array anyway?

like image 263
user1007522 Avatar asked Oct 18 '25 03:10

user1007522


2 Answers

The easiest way is to change the setting on the Gson converter so it serializes nulls - this will then send "ids":[], as you wish.

Create a new Gson instance using the GsonBuilder with serializeNulls():

private Gson gson = new GsonBuilder().serializeNulls().create();

You can then pass this to the retrofit builder when you are setting up your retrofit instance:

private Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl(API_URL)
                .addConverterFactory(GsonConverterFactory.create(gson));

Extensive configuration options are available, and listed in the Gson documentation: https://github.com/google/gson/blob/master/UserGuide.md

like image 152
rustynailor Avatar answered Oct 20 '25 16:10

rustynailor


I had this situation I managed to deal with it by telling the backend developer which im working with to accept a list contains an empty string and he will deal with it as empty list and it worked fine with me just made simple condition in the parameter of the service

if(list.isEmpty()) listOf(“”) else list
like image 25
Mohamed Shawky Avatar answered Oct 20 '25 18:10

Mohamed Shawky