3

I'm having a bit of trouble with GSON reading my API response JSON.

My API data returns an object with a status code, message and a data object.

The problem that I have with GSON, is that I can't figure out how to work with it properly.

For example, my API response can look like this.

{
    "code": 200,
    "message": "",
    "data": {
        "auth_token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        "points": 42850
    }
}

OR

{
    "code": 200,
    "message": "",
    "data": {
        "items": [
          {
            "title" : "value"
          },
          {
            "title" : "value"
          }
        ]
    }
}

OR others

The first response, which is a login response would be a class LoginResponse.class

public class LoginResponse {

    private String auth_token;
    private int points;

    public String getAuthToken(){
        return auth_token;
    }

    public int getPoints(){
        return points;
    }

}

and I'd use

LoginResponse response = gson.fromJson(json, LoginResponse.class);

But, how can I create a class so I can access the status code, message and the data? (which could be any of the response classes that I have)

I've looked at TypeAdapterFactory and JsonDeserializer, but couldn't get my head around it.

So, if anyone can find a SO answer that answers this question, that'd be great because I couldn't find one, or if you know how to do just this.

2 Answers 2

1

You could have code and message as normal, and then data could be a Map<String, Object> that you would have to interpret at runtime depending on the code or whatever you use to differentiate how the response should look.

Sign up to request clarification or add additional context in comments.

Comments

0

You can solve it by doing this:

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

JsonParser parser = new JsonParser();
JsonObject rootObejct = parser.parse(json).getAsJsonObject();
JsonElement dataElement = rootObejct.get("data");
LoginResponse response = gson.fromJson(dataElement, LoginResponse.class);

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.