Retrofit POST with json object containing parameters

I use Retrofit to send a POST request to my server:

 @POST("/login") void login( @Body User user ,Callback<User> callback); 

Where my user object has only email and password fields.

Checking the logs, I see that my parameters are sent with this format:

 D/Retrofit﹕{"email":" example@test.com ","password":"asdfasdf"} 

What do I need to do so that my parameters are sent like this?

 {"user" : {"email":" example@test.com ","password":"asdfasdf"} } 
+5
source share
2 answers

EDIT: The correct way using a custom JsonSerializer :

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

And then, on your API client API client:

 public static RestApiClient buildApiService() { Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .registerTypeAdapter(User.class, new CustomGsonAdapter.UserAdapter()) .create(); RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(API_URL) .setConverter(new GsonConverter(gson)) .build(); return restAdapter.create(MudamosApi.class); } 
+6
source

The easiest way to solve your problem is to create a RequestPOJO class, for example:

User.java file:

 public class User{ public String email; public String password; } 

File LoginRequestPojo.java:

 public class LoginRequestPojo{ public User user; public LoginRequestPojo(User user){ this.user = user; } } 

And in the request for your update 2:

 @POST("/login") void login( @Body LoginRequestPojo requestPojo, Callback<User> callback); 

Finally, your request object:

{"user":{"email":" someone@something.com ","password":"123123" }}

+1
source

Source: https://habr.com/ru/post/1205320/


All Articles