I\'m consuming an API from my android app, and all the JSON responses are like this:
{
\'status\': \'OK\',
\'reason\': \'Everything was fine\',
\
As per answer of @Brian Roach and @rafakob i done this in the following way
Json response from server
{
"status": true,
"code": 200,
"message": "Success",
"data": {
"fullname": "Rohan",
"role": 1
}
}
Common data handler class
public class ApiResponse {
@SerializedName("status")
public boolean status;
@SerializedName("code")
public int code;
@SerializedName("message")
public String reason;
@SerializedName("data")
public T content;
}
Custom serializer
static class MyDeserializer implements JsonDeserializer
{
@Override
public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException
{
JsonElement content = je.getAsJsonObject();
// Deserialize it. You use a new instance of Gson to avoid infinite recursion
// to this deserializer
return new Gson().fromJson(content, type);
}
}
Gson object
Gson gson = new GsonBuilder()
.registerTypeAdapter(ApiResponse.class, new MyDeserializer())
.create();
Api call
@FormUrlEncoded
@POST("/loginUser")
Observable> signIn(@Field("email") String username, @Field("password") String password);
restService.signIn(username, password)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer>() {
@Override
public void onCompleted() {
Log.i("login", "On complete");
}
@Override
public void onError(Throwable e) {
Log.i("login", e.toString());
}
@Override
public void onNext(ApiResponse response) {
Profile profile= response.content;
Log.i("login", profile.getFullname());
}
});