CherryBelle
CherryBelle

Reputation: 1422

Retrofit - Send request body as array or number

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?

Upvotes: 0

Views: 1440

Answers (1)

Macmist
Macmist

Reputation: 723

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

Upvotes: 1

Related Questions