Retrofit error: BEGIN_ARRAY expected, but STRING

Sometimes the api response can be an array, sometimes it can be a string.

Here's an array in detail

 {  "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 there may be a line

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

      

The line is detailed here

How to get value from this response type

My current ad

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

      

Anyone please help me find a solution?

+3


source to share


2 answers


Have you tried with a raw type of answer?

@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 getStringFromRetrofitRespone can 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();

}

      

+4


source


I think you can write your own deserializer for use in modification, but it also works by simply inferring that it is an object and then processing it later in your code.



@SerializedName(value="details")
public Object details;

      

0


source







All Articles