11

I am working on Retrofit, but I am stuck on one thing: how do I get the raw JSON on the response body.

public interface ViewMenuItems {
  @GET
  Call<ResponseBody> listRepos(@Url String url);
}

ViewMenuItems viewMenuItems = ApiClient.getClient().create(ViewMenuItems.class);
  Call<ResponseBody> responseBodyCall = viewMenuItems.listRepos(Webservices.MERCHANT + merchantId + Webservices.MENU_ITEMS_LASTMODIFIED);

       responseBodyCall.enqueue(new Callback<ResponseBody>() {
       @Override
       public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
          Log.d("MenuItems", "Response :: " + response.body().toString());
       }

       @Override
       public void onFailure(Call<ResponseBody> call, Throwable t) {
         Log.d("MenuItems", "Exception :: " + t.toString());
       }
 });

But in the "MenuItems" log I am not getting the JSON response, it's coming something like this

MenuItems: Response :: retrofit2.Response@e292dd4

Please kindly go through my post and suggest me some solution.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Anshuman Pattnaik
  • 143
  • 1
  • 1
  • 7
  • 2
    Have you tried to call `body().string()` instead of `body().toString()`? – Salem Aug 09 '16 at 21:40
  • Possible duplicate of [Can't get OkHttp's response.body.toString() to return a string](http://stackoverflow.com/questions/28300359/cant-get-okhttps-response-body-tostring-to-return-a-string) – OneCricketeer Aug 09 '16 at 21:51

2 Answers2

36

Try to use body().string() instead of body().toString()

Salem
  • 12,808
  • 4
  • 34
  • 54
  • @Salem How do I parse the Json object and Json arrays which is present in that string – Prabs Dec 27 '16 at 13:22
  • @Prabs You cna use any library of your choice: [gson](https://github.com/google/gson), Jackson or even the default JSONObject: http://stackoverflow.com/a/9606629/1205368 – Salem Dec 27 '16 at 20:34
  • @Salem I've done this - `JSONObject jObject = new JSONObject(response.body().string());` then use that Json object to fetch arrays and objects within it – Prabs Dec 28 '16 at 05:12
  • 3
    @AhmedMousa I think it's removed in Retrofit2 – Marty Miller Jun 07 '17 at 18:10
  • 1
    @AhmedMousa try raw().body().string() – Dustin Kendall Jun 30 '17 at 20:11
  • I had to cast it, otherwise it assumes my dto type String body = ((ResponseBody) response.body()).string(); – Don May 10 '19 at 18:52
5

Use Call<JSONObject>. That way you don't even need to include any of retrofit converters in your project.

maciekjanusz
  • 4,702
  • 25
  • 36
  • That doesn't quite answer the question. Plus, what if the deserialization of the JSON was actually wanted? – OneCricketeer Aug 09 '16 at 21:48
  • True, I didn't spot the `on response body` part of the question. Although, this is still valid, for the deserialization one can use any method inside the response callback, although I admit that most of the times it's not the best idea. – maciekjanusz Aug 09 '16 at 21:59