Handle different JSON response types from same endpoint in RetroFit

前端 未结 3 658
悲&欢浪女
悲&欢浪女 2021-01-17 16:04

I need help.

I have an endpoint that takes a parameter. Depending on this parameter, the JSON returned will be completely different.

Is it possi

相关标签:
3条回答
  • 2021-01-17 16:55

    you can use JsonElement in such as follow : in ApiInterface.java :

    @GET("web api url")
    Call<JsonElement> GetAllMyClass();
    

    than in MyActivity :

    ApiInterface client = ApiClient.getClient().create(ApiInterface.class);
    
        Call<JsonElement> call = client.GetAllMyClass();
        call.enqueue(new Callback<JsonElement>() {
           @Override
           public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
                    if (response.isSuccessful()) {
                         JsonElement questions = response.body();
    
     // if response type is array
                         List<MyClass> response_array = new Gson().fromJson(((JsonArray)questions), new TypeToken<List<MyClass>>(){}.getType());
    
     // if response type is object
                         MyClass response_one = new Gson().fromJson(questions.getAsJsonObject(), MyClass.class);
                     } else {
                          Log.d("MyClassCallback", "Code: " + response.code() + " Message: " + response.message());
                            }
                        }
    
          @Override
          public void onFailure(Call<JsonElement> call, Throwable t) {
                   t.printStackTrace();
           }
        });
    
    0 讨论(0)
  • 2021-01-17 17:02

    Just to close this off.

    You can get the raw JSON back from RetroFit and use GSON to manually serialise to the class type you want.

    For example:

    RestClient.get().getDataFromServer(params, new Callback<JSONObject>() {
        @Override
        public void success(JSONObject json, Response response) {
            if(isTypeA) {
                //Use GSON to serialise to TypeA        
            } else {
                //Use GSON to serialise to TypeB
            }
        }
    });
    
    0 讨论(0)
  • 2021-01-17 17:03

    In this response, since it is only change in the fields but not the structure like array or object. In that case just define all the fields in the java object, the values that will be returned in that specific call will be mapped and the others will be null. Put a logic on your end to check null checks.

    0 讨论(0)
提交回复
热议问题