0

I want to read response as a custom class but I have to use ResponseBody as a parameter in Post method.

Post interface :

public interface IPostPhoneToken {
@FormUrlEncoded
@POST()
Call<ResponseBody> postPhoneToken(
        @Field("data[UserPhoneToken][first_name]") String firstName,
        ...
        @Url String endpoint);
}

Problem is here :

 call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if(response.isSuccessful()){
            }
            else{
                System.out.println(response.message());
            }
        }
        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            System.out.println("Failed");
        }
    });

I want to change ResponseBody with different Class to be able to read response values.

Thanks.

Community
  • 1
  • 1
user3817558
  • 91
  • 1
  • 12

1 Answers1

1

You can use Response<JsonElement> and get as Json object your response and after that use any json deserializer to convert to your class.

call.enqueue(new Callback<JsonElement>() {
    @Override
    public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
        if(response.isSuccessful()){
            JsonElement jsonElement = response.body();
            JsonObject objectWhichYouNeed = jsonElement.getAsJsonObject();

            //use any json deserializer to convert to your class.
        }
        else{
            System.out.println(response.message());
        }
    }
    @Override
    public void onFailure(Call<JsonElement> call, Throwable t) {
        System.out.println("Failed");
    }
});
Community
  • 1
  • 1
kkost
  • 3,640
  • 5
  • 41
  • 72