Search code examples
androidretrofitretrofit2

How to get JSON object using Retrofit?


I'm trying to read this JSON using Retrofit but I got this error Could not locate ResponseBody converter for class org.json.JSONObject.

The JSON in ALE2 file

{
   "a1":[...],
   "a2":[...],
   "a3":[...]
}

Code

Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.BASE_URL).build();
retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback < JSONObject > () {
    @Override
    public void onResponse(Call < JSONObject > call, Response < JSONObject > response) {

    }

    @Override
    public void onFailure(Call < JSONObject > call, Throwable t) {

    }
});

RetrofitInterface

public interface RetrofitInterface {

    @GET("ALE2")
    Call<JSONObject> getData();

}

I don't want to store them in any model I just want to get the JSON as a string


Solution

  • Your interface should look like this :

    public interface RetrofitInterface {
        @GET("ALE2")
        Call<ResponseBody> getData();
    }
    

    To get raw json object return type should be Call<ResponseBody> Once that is done in response you can handle it like below :

    retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback<ResponseBody> () {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String responseBody = response.body().string();
                JSONObject json = new JSONObject(responseBody);
            }
    
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
    
            }
        });
    

    This is how you can set string in JSON object.