16

I need to send a list / an array of Integer values with Retrofit to the server (via POST) I do it this way:

@FormUrlEncoded
@POST("/profile/searchProfile")
Call<ResponseBody> postSearchProfile(
        @Field("age") List<Integer> age
};

and send it like this:

ArrayList<Integer> ages = new ArrayList<>();
        ages.add(20);
        ages.add(30);

ISearchProfilePost iSearchProfile = gsonServerAPIRetrofit.create(ISearchProfilePost.class);
        Call<ResponseBody> call = iSearchProfile.postSearchProfile(
                ages
        );

The problem is, the values reach the server not comma separated. So the values there are like age: 2030 instead of age: 20, 30.

I was reading (e.g. here https://stackoverflow.com/a/37254442/1565635) that some had success by writing the parameter with [] like an array but that leads only to parameters called age[] : 2030. I also tried using Arrays as well as Lists with Strings. Same problem. Everything comes directly in one entry.

So what can I do?

Community
  • 1
  • 1
Tobias Reich
  • 4,952
  • 3
  • 47
  • 90
  • Check that solution as well, I am following Gson to solve a similar problem https://stackoverflow.com/a/64621637/12228284 – Rahul Oct 31 '20 at 12:22

3 Answers3

21

To send as an Object

This is your ISearchProfilePost.class

@FormUrlEncoded
@POST("/profile/searchProfile")
Call<ResponseBody> postSearchProfile(@Body ArrayListAge ages);

Here you will enter the post data in pojo class

public class ArrayListAge{
    @SerializedName("age")
    @Expose
    private ArrayList<String> ages;
    public ArrayListAge(ArrayList<String> ages) {
        this.ages=ages;
    }
}

Your retrofit call class

ArrayList<Integer> ages = new ArrayList<>();
        ages.add(20);
        ages.add(30);

ArrayListAge arrayListAge = new ArrayListAge(ages);
ISearchProfilePost iSearchProfile = gsonServerAPIRetrofit.create(ISearchProfilePost.class);
Call<ResponseBody> call = iSearchProfile.postSearchProfile(arrayListAge);

To send as an Array List check this link https://github.com/square/retrofit/issues/1064

You forget to add age[]

@FormUrlEncoded
@POST("/profile/searchProfile")
Call<ResponseBody> postSearchProfile(
    @Field("age[]") List<Integer> age
};
SymbolixAU
  • 25,502
  • 4
  • 67
  • 139
Panneer Selvam R
  • 443
  • 3
  • 11
2

Retrofit can do this now at least I tested with this -> implementation 'com.squareup.retrofit2:retrofit:2.1.0'

For example

@FormUrlEncoded
@POST("index.php?action=item")
Call<Reply> updateStartManyItem(@Header("Authorization") String auth_token, @Field("items[]") List<Integer> items, @Field("method") String method);

This is the piece we are looking at.

@Field("items[]") List<Integer> items
Goddard
  • 2,863
  • 31
  • 37
0

If you want to upload array of object using Retrofit then follow the steps. It will work 100%. In my case I have 2 params one is userId and second is location_data. In second params I have to pass array of objects.

@FormUrlEncoded
@POST("api/send_array_data")
Call<StartResponseModal> postData(@Field("user_id") String user_id,
                                             @Field("location_data") String 
jsonObject);

then in your MainActivity.class / Fragments.

 ArrayList<JSONObject> obj_arr;  // define this at top level.
 try {
                JSONArray jsonArray = new JSONArray();
                obj_arr = new ArrayList<>();
                 // LocationData is model class. 
                for (LocationData cart : arrayList) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("latitude", cart.getLatitude());
                    jsonObject.put("longitude", cart.getLongitude());
                    jsonObject.put("address", cart.getAddress());
                    jsonObject.put("battery", cart.getBattery());
                    jsonObject.put("is_gps_on", cart.getIs_gps_on());
                    jsonObject.put("is_internet_on", 
                     cart.getIs_internet_on());
                    jsonObject.put("type", cart.getType());
                    jsonObject.put("date_time", cart.getDate_time());
                    jsonArray.put(jsonObject);
                    obj_arr.add(jsonObject);
                }
                Log.e("JSONArray", String.valueOf(jsonArray));
            } catch (JSONException jse) {
                jse.printStackTrace();
            }




 String user_id = SharedPreferenceUtils.getString(getActivity(), 
 Const.USER_ID);
    RetrofitAPI retrofitAPI = 
 APIClient.getRetrofitInstance().create(RetrofitAPI.class);
    Call<StartResponseModal> call = 
 retrofitAPI.postData(user_id,obj_arr.toString());
    call.enqueue(new Callback<StartResponseModal>() {
        @Override
        public void onResponse(Call<StartResponseModal> call, 
  Response<StartResponseModal> response) {
            // Handle success
            if (response.isSuccessful() && 
  response.body().getErrorCode().equals("0")) {
                // Process the response here
                Log.e("Hello Room data send","Success");
                deleteItemsFromDatabase();


            } else {
                // Handle API error
                Log.e("Hello Room data send","failed else");

            }
        }

        @Override
        public void onFailure(Call<StartResponseModal> call, Throwable t) {
            // Handle failure
            Log.e("Hello Room send","failure");

        }
    });
Rakesh Jha
  • 279
  • 2
  • 7