Search code examples
javaandroidrestandroid-annotations

How to parse JSON Response to POJO with AndroidAnnotations?


I'm using AndroidAnnotations to build a Rest for an Android Application. On the Serverside im using PHP, which send a json looking like :

{"tag":"register","success":0,"error":2,"msg":"User already existed","body":[]}

I have two POJOS :

User.java:

public class User implements Serializable {
    private String name;
private String email;
private String password;

    //getter and setter Methods
}

Response.java:

public class RegistrationResponse implements Serializable {

private String tag;
private int success;
private int error;
private String msg;
private String body;

    //getter and setter Methods
}

Rest Client:

@Rest(rootUrl = "http://my.domain.com", converters = {
    MappingJacksonHttpMessageConverter.class,
    StringHttpMessageConverter.class, GsonHttpMessageConverter.class }, interceptors = { MyInterceptor.class })
public interface RestClient extends RestClientErrorHandling {
    @Post("/user/register/{name}/{email}/{pass}")
    @Accept(MediaType.APPLICATION_JSON_VALUE)
    Response sendUserRegistration(User user, String name, String email,
        String pass);

    RestTemplate getRestTemplate();
}

Activity.java:

//User and Response are POJOs
Response result = RestClient.sendUserRegistration(user,
                user.getName(),user.getEmail(),user.getPassword());

But i got an Null Pointer Exception error on Activity.java. But if i change the return value of "sendUserRegistration" function to String all work. So my "Response" POJO seems not to be converted from AndroidAnnotations.

How can i convert the Rest Response to my "Response"-POJO using AndroidAnnotations?


Solution

  • You don't need to return the entire response object per rest call, just set the response to your custom object. Or you can also return a JsonObject also and use gson to convert it later on.

    @Rest(rootUrl = "http://my.domain.com", converters = {
    MappingJacksonHttpMessageConverter.class,
    StringHttpMessageConverter.class, GsonHttpMessageConverter.class }, interceptors = {   MyInterceptor.class })
    public interface RestClient extends RestClientErrorHandling {
    
        @Post("/user/register/{name}/{email}/{pass}")
        @Accept(MediaType.APPLICATION_JSON_VALUE)
        User sendUserRegistration(User user, String name, String email,
        String pass);
    
        RestTemplate getRestTemplate();
    }
    

    then just simply call

    User newUser = RestClient.sendUserRegistration(user,
                    user.getName(),user.getEmail(),user.getPassword());