Kayan Almeida Kayan Almeida - 2 years ago 268
JSON Question

Retrofit POST with a json object containing parameters

I'm using Retrofit to send a

request to my server:

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

Where my
object has only

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


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

{"user" : {"email":"example@test.com","password":"asdfasdf"} }

Answer Source

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()
            .registerTypeAdapter(User.class, new CustomGsonAdapter.UserAdapter())

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setConverter(new GsonConverter(gson))
    return restAdapter.create(MudamosApi.class);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download