'Retrofit 2 send an empty array
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?
Solution 1:[1]
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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | rustynailor |
Solution 2 |