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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With