0

I've this kind of json response:

 {
  error: false
  stats: {
          punti: 150
          punti2: 200
         }-
 }

I created a StatsReceiver class:

public class StatsReceiver {
 Boolean error;
 Stats stat;

 public Boolean isError() {
     if (error == null)
         return true;
     else
         return error;
 }

 public int getPunti() {
     if (stat == null)
         return -1;
     else
         return stat.getPunti();
 }

 private class Stats {
     private int punti = 0;

     public int getPunti() {
         return punti;
     }

    public void setPunti(int punti) {
         this.punti = punti;
     }

     public int getPunti2() {
         return punti2;
     }

     public void setPunti2(int punti2) {
         this.punti2 = punti2;
     }

     private int punti2 = 0;

     public Stats(int punti, int punti2) {
         this.punti = punti;
         this.punti2 = punti2;
     }
 }
}

Next:

 @GET("/v1/stats")
 void stats(@Header("Auth") String code,
              Callback<StatsReceiver> object);

Now when I do:

 apiServiceUsers.stats(apiKey, new Callback<StatsReceiver>() {
        @Override
        public void success(StatsReceiver statsReceiver, Response response) {
            if (statsReceiver.isError()) {
                Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, statsReceiver.getPunti(), Toast.LENGTH_LONG).show();
            }
        }

Error is false as expected, but getPunti() return always -1, so stat object is always null.

What's wrong?

P.S in the Log console, there is:

 {"error":false,"stats":{"punti":150,"punti2":200}}

1 Answer 1

1

In your JSON example the key is stats; but in your Java class the member variable is called stat. For Gson to work, these must be either exactly the same, or you must use @SerializedName to tell Gson which JSON key corresponds to which variable:

@SerializedName("stats")
Stats statOrSomethingElseEntirely;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.