3

Can I download json object as a String without parsing with Retrofit on Android device?

When I tried direct approach

@GET("/api.php?action=bundle")
public void getWholeScheduleString(Callback<String> response);

I got error:

"com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected a string but was BEGIN_OBJECT at line 1 column 2 path $"
Besuglov Sergey
  • 506
  • 5
  • 20
  • see this http://stackoverflow.com/questions/31898210/retrofit-jsonobject-jsonobject – b-h- Aug 08 '15 at 20:39

3 Answers3

5

Instead of Callback<String> response, you can use Callback<Response> response, so your code will look like that:

@GET("/api.php?action=bundle")
public void getWholeScheduleString(Callback<Response> response);

Afterwards, you can access body of the response in the following way:

response.getBody().toString();

I am not sure if it will work correctly, but you can try that.

Piotr Wittchen
  • 3,853
  • 4
  • 26
  • 39
  • TypedByteArray[length=5791066] is not exactly what I wanted, but I guess I'am close. – Besuglov Sergey Feb 21 '15 at 12:51
  • Actually, the `Response` contains a stream still to be read. See [this answer](http://stackoverflow.com/questions/22325641/retrofit-callback-get-response-body). – nhaarman Feb 21 '15 at 13:09
  • Niek is right. `Response.getBody()` returns stream instead of String. I found thread describing how to convert `TypedInput` to `String`. Check it here: http://stackoverflow.com/a/22820153/1150795 . `TypedInput` will be returned in `response.getBody()` method. – Piotr Wittchen Feb 21 '15 at 13:11
5

This happens because the response is a JSON Object and not a String. You could do the following: First change the getter method:

@GET("/api.php?action=bundle")
public void getWholeScheduleString(Callback<JsonObject> response);

Then in the success(JsonObject json, Response res) method of your Callback you just map it to a String:

@Override
public void success(JsonObject response, Response arg1) {
    String myResponse = response.getAsString();
}

EDIT: By the way, you can parameterize the query part (?action=bundle) to make the method more generic like this:

@GET("/api.php")
public void getWhateverAction(@Query("action") String action, Callback<JsonObject> response);

You pass the 'action' as a String argument whenever you call the method.

Siri0S
  • 678
  • 1
  • 6
  • 10
2

You can use GSON to get the response object back to JSON string by adding this inside the success(SomeType JSON_Response_Object, Response res) method of Retrofit callback

Gson gson = new Gson();

// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(JSON_Response_Object);
Gowtham Raj
  • 2,915
  • 1
  • 24
  • 38