Handle different JSON response types from same endpoint in RetroFit

前端 未结 3 659
悲&欢浪女
悲&欢浪女 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 GetAllMyClass();
    

    than in MyActivity :

    ApiInterface client = ApiClient.getClient().create(ApiInterface.class);
    
        Call call = client.GetAllMyClass();
        call.enqueue(new Callback() {
           @Override
           public void onResponse(Call call, Response response) {
                    if (response.isSuccessful()) {
                         JsonElement questions = response.body();
    
     // if response type is array
                         List response_array = new Gson().fromJson(((JsonArray)questions), new TypeToken>(){}.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 call, Throwable t) {
                   t.printStackTrace();
           }
        });
    

提交回复
热议问题