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?

1

3 Answers 3

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
};
Sign up to request clarification or add additional context in comments.

1 Comment

Well, but this sends my object as the body but not as one "Array" among other fields. Or isn't it?
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

2 Comments

Is there a specific reason why you are using "now" version 2.1 when 2.6 is already out? Or is that supposed to mean "from 2.1 on this works"?
Just what I tested it on...edited the answer to include this detail.
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");

        }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.