Android Retrofit Posting Array

When you do a POST method on the popular plugin Retrofit on android, you normally will do something like this:

    // ApiService.java
    public interface ApiService {

        @FormUrlEncoded
        @POST("/api/login")
        public void login(@Field("email") String email, 
                          @Field("password") String password,
                          Callback<ApiKey> cb);
    }

    // MainActivity.java
    public class MainActivity extends ActionBarActivity {

        // function that calls the api service
        public void fetchProjects() {
        GlobalVariables.getRestClient().getApiService().projects(globalVariables.getApiKey(), new RestCallback<List<Project>>() {
            @Override
            public void failure(RestError restError) {
                Log.e(TAG, "failure");
                Log.e(TAG, restError.getError());
            }

            @Override
            public void success(List<Project> jsonProjects, Response response) {
                Log.d(TAG, "success");
            }
        });
    }

For details on how to do this, you can refer to this guide by Robin Chutaux.

However, when you try to POST an array, wether it’s a integer array or a string array. You might use something like this on the android client:

    // ApiService.java
    @FormUrlEncoded
    @POST("/api/projectLost")
    public void projectMarkLost(
        @Field("apiKey") String apiKey,
        @Field("project_id") int projectId,
        @Field("lost_project_remark") String lostProjectRemark,
        @Field("lost_project_reasons") ArrayList<Integer> lostProjectReasons,
        Callback<JsonObject> cb
    );

    // Content wish to post
    POST content:
    apiKey = EzAvFvScs45a2DRI0MktdIDeVRbP59
    project_id = 986
    remark = testing
    details = [detail_1,detail_2]

Then you will get something like this in the request boby:

    04-17 09:34:59.058    1037-1250/com.company.app D/Retrofit﹕ apiKey=EzAvFvScs45a2DRI0MktdIDeVRbP59&project_id=986&remark=testing&details=detail_1&details=detail_2

Which some web framework (I’m using Laravel) will have a hard time accepting it due to the double details variable is not in the proper format. Because the Retrofit library dosen’t transform your @Field("lost_project_reasons") to a array field when making the request.

To fix this problem, please add [] in the field name. For this example:

    // ApiService.java
    @FormUrlEncoded
    @POST("/api/projectLost")
    public void projectMarkLost(
        @Field("apiKey") String apiKey,
        @Field("project_id") int projectId,
        @Field("lost_project_remark") String lostProjectRemark,
        @Field("lost_project_reasons[]") ArrayList<Integer> lostProjectReasons,
        Callback<JsonObject> cb
    );

Notice the [] in field name of the 4th Field.

If you recompile your application now, your web framework should have no problem understanding your request.

7 Comments

Add yours →

  1. hi john,

    Firstly i would like to thank such a wonderful article. I recently surf like this kind of reference, its really use full for me. I need more clarification can u send the demo code for the reference. waiting for your response. Thank you by udaya from india.

    • Udaya, thank you for your comment! I’m glad that my article offered any help or insight to you. Regarding on the demo code you requested, since the application I build was very specific (it was a project management platform for a specific company), I don’t think it will help you clarify your questions but make you even more confused.

      However, take a look at this article by Robin Chutaux:
      http://blog.robinchutaux.com/blog/a-smart-way-to-use-retrofit/.
      It walks you through some standard practices and code structures about using Retrofit, which I find it very helpful!

      Hope it helps!

  2. Thank you so much. You made my day.

  3. I try this way,but I get the request params like this “details[]=detail_1&details[]=detail_2”.Please give me a hand ,thx~

    • Hello , I have the same problem
      Did you find a way to fill index in details[] array ??

      expected output: “details[0]=detail_1&details[1]=detail_2”

  4. Nishad Vadgama

    April 3, 2017 — 7:43 pm

    not working for me.. please help..
    i want to post request below json..
    {
    “token” : “token_value”,
    “contacts” : [
    { “email_id” : “[email protected]” },
    { “email_id” : “[email protected]” },
    { “email_id” : “[email protected]” },
    { “email_id” : “[email protected]” },
    { “email_id” : “[email protected]” },
    { “email_id” : “[email protected]” },
    { “email_id” : “[email protected]” }
    ]
    }

    i’m trying a lot but didn’t getting it right…

  5. hello it is very helpful for me can you please show a complete example of the “Post an array in android retrofit data”

Leave a Reply

Your email address will not be published. Required fields are marked *