Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit POST with a json object containing parameters

I'm using 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 can see that my parameters are sent with this format:

D/Retrofit﹕{"email":"[email protected]","password":"asdfasdf"}

What I need to do to my parameters be sent like this?

{"user" :  {"email":"[email protected]","password":"asdfasdf"} }
like image 611
Kayan Almeida Avatar asked Oct 22 '14 23:10

Kayan Almeida


2 Answers

EDIT: Making the right 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 builder:

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);
}
like image 153
Kayan Almeida Avatar answered Nov 15 '22 08:11

Kayan Almeida


The simplest mode to solve your problem is creating a RequestPOJO class, for example:

File User.java:

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 your retrofit 2 request:

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

Finally, your request body:

{"user":{"email":"[email protected]","password":"123123"}}

like image 20
Felipe Porge Xavier Avatar answered Nov 15 '22 10:11

Felipe Porge Xavier