Search code examples
androidarraysretrofit

How to pass Object Array on retrofit request?


I want to pass array of objects using my retrofit request. through Volley we are passing the request array as,

{OrderId=11692, ItemsList[1][Amount]=1, ItemsList[1][id]=29, ItemsList[1][Notes]=2.0, ItemsList[0][TypeId]=23, ItemsList[0][Notes]=15.0, ItemsList[1][serviceId]=28, ItemsList[0][serviceId]=27, ItemsList[0][Amount]=3, ItemsList[0][id]=29, ItemsList[1][TypeId]=23}

How I can send a request using this format?

I am trying like this:

@FormUrlEncoded
@POST("api/shidhin/UpdateOrder")
Call<CommonResponse> updateOrderItems(@Header("Authorization") String token, @Field("OrderId") int orderid, @Field("ItemsList[]") ItemsList[] itemsList);

ItemsList.java class file

public class ItemsList {
    @SerializedName("id")
    private int id;
    @SerializedName("Amount")
    private int Amount;
    @SerializedName("Notes")
    private String Notes;
    @SerializedName("serviceId")
    private int serviceId;
    @SerializedName("TypeId")
    private int TypeId;
}

Solution

  • I solved this issue by passing the object array as @FieldMap . Her is the way O solved this issue,

    Create Object Array,

            Order.Orderitems orderitems;
            Map<String, String> parms = new HashMap<String, String>();
            for (int i = 0; i < orderItems.size(); i++) {
                orderitems = orderItems.get(i);
                parms.put("ItemsList[" + i + "][id]", String.valueOf(orderitems.getId()));
                parms.put("ItemsList[" + i + "][Amount]", String.valueOf(orderitems.getAmount()));
                parms.put("ItemsList[" + i + "][Notes]", "");
                parms.put("ItemsList[" + i + "][serviceId]", String.valueOf(orderitems.getServiceId()));
                parms.put("ItemsList[" + i + "][TypeId]", String.valueOf(orderitems.getServiceTypeId()));
            }
    

    Also Made the API call Like,

    @FormUrlEncoded
    @POST("api/shidhin/UpdateOrder")
    Call<CommonResponse> updateOrderItems(@Header("Authorization") String token, @Field("OrderId") int orderid, @FieldMap Map<String, String> parms);