Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}

like image 469
RoHiT Avatar asked Dec 24 '22 11:12

RoHiT


2 Answers

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!!

like image 87
Hemant Parmar Avatar answered Dec 27 '22 03:12

Hemant Parmar


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());
        }
    });
like image 40
Chirag Avatar answered Dec 27 '22 03:12

Chirag