Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize the response body JSON conversion in Retrofit?

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?

like image 614
Henrique Avatar asked Jul 25 '14 19:07

Henrique


People also ask

How do you post raw whole JSON in the body of a retrofit request?

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.


2 Answers

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;
}
like image 187
Mubarak Mohideen Avatar answered Nov 13 '22 07:11

Mubarak Mohideen


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) {
            // ...
        }
    });
}
like image 36
chupapeng Avatar answered Nov 13 '22 08:11

chupapeng