Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit error: Expected BEGIN_ARRAY but was STRING

In api response sometimes It can be array, sometimes it can be string.

Here details is Array

 {  "ts": "2015-06-16 11:28:33","success": true,"error": false,"details": [
{
  "user_id": "563",
  "firstname": "K.Mathan"
},
{
  "user_id": "566",
  "firstname": "Surya"
},
{
  "user_id": "562",
  "firstname": "Idaya"
} ]}

Sometimes details can be string

{  "ts": "2015-06-16 11:28:33",
"success": true,
"error": false,
"details": "no data" }

Here details is String

How to get value from this type of response

My current declaration is

  @SerializedName(value="details")
   public List<detailslist> details ;

Anyone please help me to find the solution?

like image 510
Mathankumar K Avatar asked Jun 16 '15 13:06

Mathankumar K


1 Answers

Did you try with the raw response type?

@GET("your_url")
void getDetails(Callback<Response> cb);

Then you can parse the Response using JSONObject and JSONArray like this:

    Callback<Response> callback = new Callback<Response>() {
       @Override
       public void success(Response detailsResponse, Response response2) {

        String detailsString = getStringFromRetrofitResponse(detailsResponse);

        try {
            JSONObject object = new JSONObject(detailsString);

            //In here you can check if the "details" key returns a JSONArray or a String

        } catch (JSONException e) {

        }

     }

     @Override
     public void failure(RetrofitError error) {

  });

Where the getStringFromRetrofitRespone could be:

public static String getStringFromRetrofitResponse(Response response) {
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {

        reader = new BufferedReader(new InputStreamReader(response.getBody().in()));

        String line;

        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return sb.toString();

}
like image 81
Niccolò Passolunghi Avatar answered Nov 13 '22 19:11

Niccolò Passolunghi