使用 Retrofit 发送 ArrayList<Object> POST 请求

Sending ArrayList<Object> POST request with Retrofit

我想向服务器发送这样的东西

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

这是我的服务界面

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);

}

logcat显示这个

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

我有两个问题:

  1. 为什么 OrderDetailList 无法转换为 JSON。
  2. 如何为这个参数使用@FieldMap。 我最近测试 Map<String, Object> 但它 returns 结果相同。

谢谢

使用 GSON

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

像这样为您的数据创建模型

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
}

并将您的服务更改为

public interface StoreRetrofitSalesService {

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

}