retrofit – How to send a JSON via POST

Posted on

Question :

Talk to me, I’m using Retrofit 2 and I’m not able to send JSON to WS.

I have my class here that sets json the way I need it:


public class CustomGsonAdapter {
public static class UserAdapter implements JsonSerializer<NewObject> {
    public JsonElement serialize(NewObject user, Type typeOfSrc,
                                 JsonSerializationContext context) {
        Gson gson = new Gson();
        JsonElement je = gson.toJsonTree(user);
        JsonObject jo = new JsonObject();
        jo.add("order", je);
        return jo;

I also have my API builder:


  HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();

    okHttpClient = new OkHttpClient().newBuilder()
            .connectTimeout(30000*6, TimeUnit.MILLISECONDS)
            .readTimeout(30000*6, TimeUnit.MILLISECONDS)
            .writeTimeout(30000*6, TimeUnit.MILLISECONDS)

    Gson gson = new GsonBuilder()
            .registerTypeAdapter(NewObject.class, new CustomGsonAdapter.UserAdapter())

    retrofit = new Retrofit.Builder()

But now I have no idea how to handle my Request Interface :

    Call<BaseRequest> requestJson(@Body String json);

My question is whether I’m on the right track and how do I now end and send JSON to WS.


Answer :

Try this:

Instead of sending a String send a RequestBody !

Call<BaseRequest> requestJson(@Body RequestBody object);

Example to instantiate RequestBody :

 final String json  =  "{"description"": ""My description""}""

Leave a Reply

Your email address will not be published. Required fields are marked *