【问题标题】:Sending ArrayList<Object> POST request with Retrofit使用 Retrofit 发送 ArrayList<Object> POST 请求
【发布时间】:2015-12-21 05:58:07
【问题描述】:

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

{
  "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&lt;String, Object&gt;,但它返回了相同的结果。

谢谢

【问题讨论】:

    标签: android retrofit


    【解决方案1】:

    使用 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);
    
    }
    

    【讨论】:

    • 谢谢。伟大的。有用。但我想知道我是否可以使用@FieldMap 而不是创建新的订单类?因为我所有的服务方法都接受 FieldMap,所以我只想为所有人设置相同的参数。
    • @MojtabaMahamed 嗯我不这么认为,因为如果你使用 Fieldmap 它将创建一个 url 编码的参数,如果你想发送一个动态参数,我建议你通过 POST 正文以 JSON 格式发送它就像我在答案中写的一样。
    • @Niko Yuwono,如何在不使用模型的情况下将其与带有改造 2 的 mulipart partmap 一起使用??
    • @TheGreat004 你为什么要这么做?也许你可以尝试提出一个新问题。
    • @NikoYuwono,已经有很多模型类,我不想创建一个新的。
    猜你喜欢
    • 2020-04-06
    • 2015-07-22
    • 2019-12-04
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 2020-03-29
    • 2017-02-25
    • 1970-01-01
    相关资源
    最近更新 更多