Kayan Almeida Kayan Almeida - 6 months ago 58
JSON Question

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":"example@test.com","password":"asdfasdf"}


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

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

Answer

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);
}
Comments