Is it possible to use retrofit without model class?

前端 未结 5 1139
时光说笑
时光说笑 2021-01-02 02:38

i have problem to use model class in retrofit lib. A backend side field name has changed.

Is it possible to get response without model class?

相关标签:
5条回答
  • 2021-01-02 02:50

    @Vadivel here it is the version of GET based on @chetan work:

    @GET("http://your.api.url")
    Call<JsonObject> getGenericJSON();
    
    Call<JsonObject> call = api.getGenericJSON();
    call.enqueue(new Callback<JsonObject>() {
    
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            if (response.isSuccessful() && response.body() != null) {
                Log.d(TAG, response.body().toString());
            } else {
                Log.e(TAG, "Error in getGenericJson:" + response.code() + " " + response.message());
            }
        }
    
        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            Log.e(TAG, "Response Error");
        }
    });
    
    0 讨论(0)
  • 2021-01-02 02:58

    It is perfectly possible using different return values. I assume that you currently use Gson to deserialize JSON responses, and they get converted to the actual class. However, you may choose to convert the returned response to JsonElement (or some more specific JSON class), in that case you will get a JSON item which you can manipulate as you wish to. Something like:

    @GET("url")
    Call<JsonElement> apiCall();
    
    0 讨论(0)
  • 2021-01-02 03:04

    You can simply "rename" field on your side using

    @SerializedName("newFieldName")
    SomeClass oldField;
    
    0 讨论(0)
  • 2021-01-02 03:05

    Is it possible to get response without model class

    If I get you right - sure. You do not have to make response JSON auto-converted. You can do this easily by hand if needed, by retrieving raw response. Once you got that you can do whatever you need.

    0 讨论(0)
  • 2021-01-02 03:10

    Yes, you can.

    @POST("url")
    
     Call<JsonObject> register(@Query("name") String name,
    
                               @Query("password") String password);
    

    Just write JsonArray or JsonObject according to your response instead of Model class.

    Then, get data from JsonObject or JsonArray which you get in response as below

    Call<JsonObject> call = application.getServiceLink().register();
    
    call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                    JsonObject object = response.body();
                    //parse object 
                }
    
                @Override
                public void onFailure(Call<JsonObject> call, Throwable t) {
    
                }
            });
    
    0 讨论(0)
提交回复
热议问题