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"} }
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);
}
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"
}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With