Is it possible to use retrofit without model class?

此生再无相见时 提交于 2019-12-03 12:38:49

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) {

            }
        });

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();

@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");
    }
});

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.

You can simply "rename" field on your side using

@SerializedName("newFieldName")
SomeClass oldField;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!