Retrofit - Send request body as array or number

限于喜欢 提交于 2019-12-13 05:16:19

问题


I'm using Retrofit 2 and I need to send request body. The problem is somehow the value is converted to string. On the example below, you can see that items and totalPrice which should be array and number respectively are converted to string.

{ cashierId: 'fff7079c-3fc2-453e-99eb-287521feee63',
  items: '[{"amount":3,"id":"602a79e3-b4c1-4161-a082-92202f92d1d6","name":"Play Station Portable","price":1500000.0}]',
  paymentMethod: 'Debt',
  totalPrice: '4500000.0' }

The desired request body is

{ cashierId: 'fff7079c-3fc2-453e-99eb-287521feee63',
  items: [{"amount":3,"id":"602a79e3-b4c1-4161-a082-92202f92d1d6","name":"Play Station Portable","price":1500000.0}],
  paymentMethod: 'Debt',
  totalPrice: 4500000.0 }

Here's the service

@POST("api/sales")
@FormUrlEncoded
Call<Sale> createSale(
    @FieldMap Map<String, Object> fields
);

And this is how I call createSale

Map<String, Object> fields = new HashMap<>();
fields.put("cashierId", UUID.fromString("fff7079c-3fc2-453e-99eb-287521feeaaa"));
fields.put("totalPrice", totalPrice);
fields.put("paymentMethod", paymentMethod);
fields.put("items", jsonArray);

Call<Sale> call = retailService.createSale(fields);

Is it possible to send those values as number and array, not as string?


回答1:


The conversion most certainly happens because you are using @FormUrlEncoded. According to the documentation:

Field names and values will be UTF-8 encoded before being URI-encoded in accordance to RFC-3986.

A solution would be to use a model class instead of a Map. I see you already have a Sale class. If it looks like something like this:

public class Sale {
    String cashierId;
    int totalPrice;
    String paymentMethod;
    ArrayList<SomeObject> items;
}

you can simply do like this:

// in service
@POST("api/sales")
Call<Sale> createSale(@Body Sale sale);

// when doing the call
Sale sale = new Sale();
// set everything in your object
// then
Call<Sale> call = retailService.createSale(sale);


来源:https://stackoverflow.com/questions/53088208/retrofit-send-request-body-as-array-or-number

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