Search code examples
androidjsonretrofit

Getting simple JSON object response using Retrofit library


I have a web query with JSON response as:

{
    "status":true,
    "result":
      {
        "id":"1",
        "name":"ABC 1",
        "email":"info@ABc.dcom",
        "password":"123456",
        "status":false,
        "created":"0000-00-00 00:00:00"
      },
    "message":"Login successfully"
}

I am using the following code for:

@GET("/stockers/login")
public void login(
        @Query("email") String email,
        @Query("password") String password,
        Callback<JSONObject> callback);

In Debugger the query made by the Retrofit library is correct, however I get an empty JSON in response.

ApiManager.getInstance().mUrlManager.login(
        email.getText().toString().trim(),
        password.getText().toString().trim(),
        new Callback<JSONObject>()
        {
            @Override
            public void success(JSONObject jsonObj, Response response)
            {
                mDialog.dismiss();

Solution

  • Instead of Callback with JSONObject class, you could use the Retrofit basic callback which use the Response class and then, once you get the response, you had to create the JSONObject from it.

    See this: https://stackoverflow.com/a/30870326/2037304

    Otherwise you can create your own model class to handle the response.

    First the Result class:

    public class Result {
        public int id;
        public String name;
        public String email;
        public String password;
        public boolean status;
        public Date created;
    }
    

    And then your response class to use with Retrofit

    public class MyResponse {
        public boolean status;
        public Result result;
        public String message;
    }
    

    Now you can call:

     @GET("/stockers/login") 
     public void login( 
        @Query("email") String email,
        @Query("password") String password,
        Callback<MyResponse> callback);