How to handle response which can be different Type in Retrofit 2

允我心安 提交于 2019-12-03 17:05:35

For your case you can use Call<JsonElement> as response type and parse it in response:

call.enqueue(new Callback<JsonElement>() {
        @Override
        public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
            if(response.isSuccessful()){
                JsonElement jsonElement = response.body();
                if(jsonElement.isJsonObject()){
                    JsonObject objectWhichYouNeed = jsonElement.getAsJsonObject();
                } 
                // or you can use jsonElement.getAsJsonArray() method
                //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");
        }
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!