mercredi 6 mai 2015

Retrofit not parsing JSONObject

A successful login returns the following JSONObject from a server:

{"success":true,"message":"Sign in success.","response_data":{"user_id":"24", "email_id":"user@gmail.com", "secret_code": "You did it!"}}

I want to put the response_data info into my User object. I used to do something like this:

String getResponse = jsonObject.getString("response_data");

Gson gson = new GsonBuilder()
        .disableHtmlEscaping()
        .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
        .setPrettyPrinting()
        .serializeNulls()
        .create();

//All the data in the `response_data` is initialized in `User`
User user = gson.fromJson(getResponse, User.class);

Now I tried doing the same in retrofit:

Initializing RestAdapter + Interface:

public class ApiClient {
    private static RetrofitService sRetrofitService;

    public static RetrofitService getRetrofitApiClient() {
        if (sRetrofitService == null) {
            RestAdapter restAdapter = new RestAdapter.Builder()
                    .setLogLevel(RestAdapter.LogLevel.FULL)
                    .setEndpoint("http://xxx.xxx.xxx.xxx/")
                    .build();

            sRetrofitService = restAdapter.create(RetrofitService.class);
        }

        return sRetrofitService;
    }

    public interface RetrofitService {

        @FormUrlEncoded
        @POST("/login")
        public void login(@Field("email_id") String emailId, @Field ("password") String password, 
                          Callback <User> callback);                                                                    
    }
}

MainActivity:

  ApiClient.getRetrofitApiClient().login(email.getText().toString(), password.getText().toString(),       
      new Callback<User>() {
            @Override
            public void success(User user, Response response) {
                User user1 = user; //null
                Toast.makeText(this, "user is: "+user1.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void failure(RetrofitError error) {
                Toast.makeText(this, "Failed Login", Toast.LENGTH_SHORT).show();
            }
        });

User:

public class User {

    private String userId;
    private String emailId;
    private String code;

    public User() {

    }

    ... getters
    ... setters
}

The Retrofit code in MainActivity works and I get this response in my log:

{"success":true,"message":"Sign in success.","response_data":{"user_id":"24", "email_id":"user@gmail.com", "secret_code": "You did it!"}}

However it doesn't parse the response_data into my User object.

How do I fix this?

Aucun commentaire:

Enregistrer un commentaire