retrofit - How to send a JSON via POST

Asked

Viewed 4,234 times

3

Talk guys, I’m using Retrofit 2 and I’m not getting JSON to WS.

I have here my class that tidies up the 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 Builder API:

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 treat mine Request Interface:

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

My question is whether I am on the right track and how I do now to finish and send JSON to WS.

1 answer

5


Try it this way:

Instead of sending a String send a Requestbody!

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

Example to instantiate the RequestBody:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.