Sending ArrayList<Object> POST request with Retrofit

牧云@^-^@ 提交于 2020-02-04 01:19:07

问题


I want to send something like this to server

{
  "InoorPersonID": "",
  "Discount": 0,
  "DiscountDescription": "",
  "Description": "",
  "OrderDetailList": [
    {
      "ProductID": 0,
      "Amount": 0
    }
  ],
  "ClientId": "",
  "ClientSecret": ""
}

and this is my service interface

public interface StoreRetrofitSalesService {

    @FormUrlEncoded
    @POST(ServiceUrl.URL_ORDER_SET)
    Call<ServiceResult<Integer>> orderSet(@Field("OrderDetailList") ArrayList<OrderDetail> orderDetails,
                                          @Field("Discount") String discount,
                                          @Field("ClientId") String clientId,
                                          @Field("ClientSecret") String clientSecret,
                                          @Field("Description") String description,
                                          @Field("InoorPersonID") String inoorPersonId,
                                          @Field("DiscountDescription") String discountDescription);

}

The logcat show this

OrderDetailList=org.crcis.noorreader.store.OrderDetail%408208296&Discount=0&...

I have two question:

  1. Why OrderDetailList can't convert to JSON.
  2. How can I use @FieldMap for this params. I recently test Map<String, Object> but it returns same result.

Thanks


回答1:


Use GSON

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(myBaseUrl)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

Create a model for your data like this

public class Order {

    @SerializedName("InoorPersonID")
    String inoorPersonId;
    @SerializedName("Discount")
    int discount;
    @SerializedName("DiscountDescription")
    String discountDescription;
    @SerializedName("Description")
    String description;
    @SerializedName("OrderDetailList")
    ArrayList<OrderDetail> orderDetailList;
    @SerializedName("ClientId")
    String clientId;
    @SerializedName("ClientSecret")
    String clientSecret;

    //Don't forget to create/generate the getter and setter
}

And change your Service to

public interface StoreRetrofitSalesService {

    @POST(ServiceUrl.URL_ORDER_SET)
    Call<ServiceResult<Integer>> orderSet(@Body Order order);

}


来源:https://stackoverflow.com/questions/34389753/sending-arraylistobject-post-request-with-retrofit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!