retrofit - How to send a JSON via POST

3

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:

CustomGsonAdapter

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:

ApiManager

  HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
    logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);


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



    Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .registerTypeAdapter(NewObject.class, new CustomGsonAdapter.UserAdapter())
            .create();


    retrofit = new Retrofit.Builder()
            .baseUrl(endpoint)
            .client(okHttpClient)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

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

@POST("login")
    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.

    
asked by anonymous 04.05.2017 / 19:59

1 answer

5

Try this:

Instead of sending a String send a RequestBody !

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

Example to instantiate RequestBody :

 final String json  =  "{\"description\": \"My description\"}";
 RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), json);
    
04.05.2017 / 20:11