android-改装错误:预期为BEGIN_ARRAY,但为STRING

在api响应中,有时可以是数组,有时可以是字符串.

这里的细节是数组

 {  "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"
} ]}

有时细节可以是字符串

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

这里的细节是字符串

如何从这种回应中获取价值

我目前的声明是

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

任何人都可以帮助我找到解决方案吗?

解决方法:

您是否尝试过使用原始回复类型?

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

然后,您可以使用JSONObject和JSONArray解析响应,如下所示:

    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) {

  });

其中getStringFromRetrofitRespone可能是:

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();

}
上一篇:程序员怎样优雅度过35岁中年危机?绝对干货


下一篇:C图形初始化图形错误(语法或文件丢失缺陷?)