改造 - 将请求正文作为数组或数字发送 [英] Retrofit - Send request body as array or number

查看:50
本文介绍了改造 - 将请求正文作为数组或数字发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Retrofit 2,我需要发送请求正文.问题是值以某种方式转换为字符串.在下面的示例中,您可以看到分别应该是数组和数字的 itemstotalPrice 被转换为字符串.

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' }

所需的请求正文是

{ 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 }

这里是服务

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

这就是我如何调用 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?

推荐答案

转换肯定会发生,因为您使用的是 @FormUrlEncoded.根据文档:

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

字段名称和值将先进行 UTF-8 编码,然后再根据 RFC-3986 进行 URI 编码.

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

解决方案是使用模型类而不是 Map.我看到你已经有一个销售类.如果它看起来像这样:

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

你可以简单地这样做:

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

这篇关于改造 - 将请求正文作为数组或数字发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆