RoHiT
RoHiT

Reputation: 372

Handle JSON responce in retrofit 2.0

I know this is old or repeat question. But I didn't get where am I wrong. I got result null from this JSON.

{
"error": {
    "dateTimeUtc": "2017-12-26T05:46:05.1126801+00:00",
    "errorReference": "sample string 2",
    "errorType": "Error",
    "title": "sample string 3",
    "code": "sample string 4",
    "messages": [
      "sample string 1",
      "sample string 2"
    ]
  },
  "result": {
    "message": "sample string 1"
  }
}

I have this type of JSON to read from Retrofit2. I create one POJO class called RetrofitResponce

private Error error;
private Result result;
public Result getResult ()
{
    return result;
}

public void setResult (Result result)
{
    this.result = result;
}

public Error getError ()
{
    return error;
}

public void setError (Error error)
{
    this.error = error;
}

@Override
public String toString()
{
    return "ClassPojo [result = "+result+", error = "+error+"]";
}`

Now in call.enque() method to handled response, like

call.enqueue(new Callback<RegisterUser>() {
        @Override
        public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {

            try {
                RetrofitResponce retrofitResponce= response.body();

                Error error = retrofitResponce.getError();
                Result result=retrofitResponce.getResult();


                Log.e("Eroor", "rr  " + error.getTitle().toString());
            } catch (Exception e) {

            }
        }

        @Override
        public void onFailure(Call<RetrofitResponce> call, Throwable t) {
            Log.e("Failure ", "fail " + t.toString());
        }
    });

but here I get NullPointerException,i.e. I don't get any response in RestrofitResponce. Error and Result both get Null.

java.lang.NullPointerException: Attempt to invoke virtual method 'net.xyz.abc.Model.Error net.xyz.abc.Model.RegisterUser.getError()' on a null object reference

Please help me. try to solve my query.Thanks in advance.

PostMan responce,

{
"error": {
    "dateTimeUtc": "2017-12-26T07:05:51.1427712Z",
    "errorReference": "00000000-0000-0000-0000-000000000000",
    "errorType": "Error",
    "title": "The request is invalid.",
    "code": null,
    "messages": [
        "Passwords must have at least one non letter or digit character. Passwords must have at least one uppercase ('A'-'Z')."
    ]
},
"result": null

}

Upvotes: 4

Views: 169

Answers (5)

Vishal G. Gohel
Vishal G. Gohel

Reputation: 1033

I am sure this will help you.

You can not handle Success and Faille by Single model. To get error body you need to call response.errorBody().string()

Try Below Code :

call.enqueue(new Callback<RegisterUser>() {
    @Override
    public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {

       try {
                if (response.isSuccessful()) {
                Log.d("Successful",response.body();); 
                } else {
                    Log.d("errorBody ", response.errorBody().string());
                }
            } catch (Exception e) {
                Log.d("Exception ",e.toString());
            }

    }

    @Override
    public void onFailure(Call<RetrofitResponce> call, Throwable t) {
        Log.e("Failure ", "fail " + t.toString());
    }
});

Upvotes: 1

Chirag
Chirag

Reputation: 56925

You have to add the @SerializedName in your Response class for each and every filed same as the web service name.

e.g

@SerializedName("error")
private Error error;
@SerializedName("result")
private Result result;

Please use this website to create your classes from the JSON Response. http://www.jsonschema2pojo.org/

And after that you have to check if response if successful or not.

call.enqueue(new Callback<RegisterUser>() {
        @Override
        public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {

            try 
            {
                if(response.isSuccessful() && response.body() != null)
                {
                    RetrofitResponce retrofitResponce= response.body();
                    Error error = retrofitResponce.getError();
                    Result result=retrofitResponce.getResult();
                 }

            } catch (Exception e) {

            }
        }

        @Override
        public void onFailure(Call<RetrofitResponce> call, Throwable t) {
            Log.e("Failure ", "fail " + t.toString());
        }
    });

Upvotes: 3

mehul chauhan
mehul chauhan

Reputation: 1802

Try this.

    call.enqueue(new Callback<RetrofitResponce>() {
    @Override
    public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {

        if (response.body() != null)

       Toast.makeText(YourActivity.this,response.body().getResult(), 
       Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onFailure(Call<RetrofitResponce> call, Throwable t) {
        Log.e("Failure ", "fail " + t.toString());
    }
});

Upvotes: 1

Hemant Parmar
Hemant Parmar

Reputation: 3976

Retrofit callback needs response model, just change this:

call.enqueue(new Callback<RetrofitResponce>() {
        @Override
        public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {


                if (response.isSuccessful()) {
                RetrofitResponce retrofitResponce= response.body();
                if (retrofitResponce!=null) {   
                Error error = retrofitResponce.getError();
                Result result=retrofitResponce.getResult();       
                Log.e("Eroor", "rr  " + error.getTitle().toString());
              }
            }                
        }

        @Override
        public void onFailure(Call<RetrofitResponce> call, Throwable t) {
            Log.e("Failure ", "fail " + t.toString());
        }
    });

Happy coding!!

Upvotes: 3

Ramesh sambu
Ramesh sambu

Reputation: 3539

Try this Pojo for RetrofitResponce

public class RetrofitResponce {

@SerializedName("error")
@Expose
private Error error;
@SerializedName("result")
@Expose
private Result result;

public Error getError() {
return error;
}

public void setError(Error error) {
this.error = error;
}

public Result getResult() {
return result;
}

public void setResult(Result result) {
this.result = result;
}

}


public class Result {

@SerializedName("message")
@Expose
private String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

}


public class Error {

@SerializedName("dateTimeUtc")
@Expose
private String dateTimeUtc;
@SerializedName("errorReference")
@Expose
private String errorReference;
@SerializedName("errorType")
@Expose
private String errorType;
@SerializedName("title")
@Expose
private String title;
@SerializedName("code")
@Expose
private String code;
@SerializedName("messages")
@Expose
private List<String> messages = null;

public String getDateTimeUtc() {
return dateTimeUtc;
}

public void setDateTimeUtc(String dateTimeUtc) {
this.dateTimeUtc = dateTimeUtc;
}

public String getErrorReference() {
return errorReference;
}

public void setErrorReference(String errorReference) {
this.errorReference = errorReference;
}

public String getErrorType() {
return errorType;
}

public void setErrorType(String errorType) {
this.errorType = errorType;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public List<String> getMessages() {
return messages;
}

public void setMessages(List<String> messages) {
this.messages = messages;
}

}

Upvotes: 2

Related Questions