How to handle Dynamic JSON in Retrofit?

后端 未结 10 2381
余生分开走
余生分开走 2020-11-22 16:23

I am using the retrofit efficient networking library, but I am unable to handle Dynamic JSON which contains single prefix responseMessage which changes to

10条回答
  •  孤街浪徒
    2020-11-22 17:08

    I know I am late, but I just want to share my thought. I was working on a project where I am writing a method. The method uses retrofit to get data from server. Since other developers in my company will use this method, I could not use a POJO class (in your example, the TrackerRefResponse class). So I used JsonObject / Object like this:

    interface APIService.java

    public class APIService{
        @FormUrlEncoded
        @POST
        Call myPostMethod(@Url String url, @Field("input") String input);
    }
    

    Then in my method, I wrote this:

    Call call = RetrofitClient.getAPIService().establishUserSession(post_request_url, someParameter);
    
    call.enqueue(new Callback() {
                @Override
                public void onResponse(Call call, Response response) {
                    JsonObject jsonObject = response.body();
                    String jsonString = response.body().toString();
                    // then do your stuff. maybe cast to object using a factory pattern  
        }
    // rest of the code
    }
    
    

    You can also use Object instead of 'JsonObject`. Later, when you will know which kind of response it is, maybe you can cast this into desired object.

提交回复
热议问题