Can you please tell me how to send a POST request in JSON format in Retrofit 2? The request is as follows:

{ datetime: 0, body: { gymId: '3422342342423424', customerName: 'test', customerEmail: 'test@test.ru', content: 'test' } } 

1 answer 1

I use for this purpose LoganSquare.

You connect to gradle LoganSquare and LoganSquareConverter (com.github.aurae.retrofit2: converter-logansquare: 1.4.0 ').

After you create models:

To request:

 @JsonObject public class Request{ @JsonField(name = "datetime") int datetime; @JsonField(name = "body") Model body; /* тут создаешь пустой конструктор и конструктор для всех переменных*/ } 

Auxiliary:

 @JsonObject public class Model{ @JsonField(name = "gymId") String gymId; @JsonField(name = "customerName") String customerName; @JsonField(name = "customerEmail") String customerEmail; @JsonField(name = "content") String content; /* тут создаешь пустой конструктор и конструктор для всех переменных*/ } 

Next, in the Retorfit interface, you describe the method:

 @Headers("Content-Type: application/json") @POST(/*url метода (допустим "/mymetod"*/) Call myMetod(@Body Request body); 

Next, execute the query itself:

 Retrofit retrofit = new Retrofit.Builder() .baseUrl(/*BASE URL "например 192.168.1.1:6666"*/) .addConverterFactory(LoganSquareConverterFactory.create()) .build(); RetrofitAPI service = retrofit.create(RetrofitAPI.class); Call<Request> call = service.myMetod(/* тут создаешь модель*/ new Request(0, new Model("1235464", "test", "test@test.ru", "test")); call.enqueue(new Callback<MarketResponse>() { @Override public void onResponse(Call<Request> call, Response<Request> response) { } @Override public void onFailure(Call<Request> call, Throwable t) { } });