I'm using Retrofit to implement a Rest Client and I ran into some trouble when trying to convert the response body to my model Object.
I have the following in my interface:
@POST("/users")
void createUser(@Body RegisterUserToken token, Callback<User> callback);
My User
class is basically a POJO with:
public class User {
private int id;
private String username;
private String email;
private String language;
// getters and setters...
}
And this is how I use the Rest Client:
restClient.createUser(token, new Callback<User>() {
@Override
public void success(User user, Response response) {
// ...problem is here, with the user object
}
@Override
public void failure(RetrofitError error) {
// ...
}
});
The problem I'm having is that the response body is not being converted to a User
object. I'm pretty sure the problem is that the server is returning:
{"user":{"id":13,"username":"john","email":"[email protected]","language":"eng"}}
Instead of just:
{"id":13,"username":"john","email":"[email protected]","language":"eng"}
Given that I can't really modify the server code, how can I customize Retrofit/GSON to correctly convert this response body to my User object?
change your call interface @Body parameter to String, don't forget to add @Headers("Content-Type: application/json") : @Headers("Content-Type: application/json") @POST("/api/getUsers") Call<List<Users>> getUsers(@Body String rawJsonString); now you can post raw json.
Change the POJO class like this:
public static class User {
UserData user;
}
public static class UserData {
private int id;
private String username;
private String email;
private String language;
}
try using Map<String,User>
instead of just User
. To get the actual User
object, you can then access the User
object by using the key "user" on the map.
for example:
@POST("/users")
void createUser(@Body RegisterUserToken token, Callback<Map<String, User>> callback);
restClient.createUser(token, new Callback<Map<String, User>>() {
@Override
public void success(Map<String, User> map, Response response) {
User user = map.get("user");
}
@Override
public void failure(RetrofitError error) {
// ...
}
});
}
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