Skip to content Skip to sidebar Skip to footer

Sending List Of Objects In Form-urlencoded Request Using Retrofit2

This is my postman request: I'm going to send a POST request using Retrofit2, Gson and RxJava2. This is my request: @FormUrlEncoded @POST('Student') // I'm sure the address and na

Solution 1:

May be you can try with this:

@FormUrlEncoded@POST("Student") // I'm sure the address and name are correctCompletableStudent(@Field("firstName") String firstName,
                    @Field("lastName") String lastName,
                    @FieldMapMap<String, String>
);

  *****************************
// how to use the mapMap<String, String> params = newHashMap<>();
params.put("exam[0][field]","Math");
params.put("exam[0][score]","90");
params.put("exam[1][field]", "Physics");
params.put("exam[1][score]", "99");

Solution 2:

If the Postman request works then this would be the Retrofit equivalent:

@FormUrlEncoded@POST("Student")
Completable Student(@Field("firstName") String firstName,
                    @Field("lastName") String lastName,
                    @FieldMap Map<String, String> fieldMap
);

and then run a loop to fill in the details

publicvoidsendRequest(List<Exam> exams) {
    Map<String, String> map = newHashMap<>();
    for (int i = 0; i < exams.size(); i++) {
        map.put("exam[" + i + "].field", exams.get(i).getField());
        map.put("exam[" + i + "].score", String.valueOf(exams.get(i).getScore()));
    }
    yourApiService.Student(firstName, lastName, map); // enqueue or execute whatever
}

This is more of a simpler approach you could also look into custom a JsonSerializer with Gson.

Post a Comment for "Sending List Of Objects In Form-urlencoded Request Using Retrofit2"