改造解析空数组[]

Retrofit parse empty array []

我需要解析对象列表,可以使用。 {"data":[]} 我使用模板回调 CallBack<T> 调用

public static DataList {
    public List<Data> data
};

api.getData(new Callback<DataList>() {...});

它因错误而崩溃:java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com...DataList 请帮助

您的问题是您的 java 模型没有反映它试图反序列化的数据。

//{"data":[]} does not map to List<Data> data. 
// If the server was just returning an array only then it would work. 
// It will match to the entity below make sure your cb = Callback<MyItem>
public class MyItem {
    List<Data> data;
}

您的模型应该可以正常工作。也许您的服务器没有 return 像您认为的那样,或者它可能 application/json 没有像 return 那样?

这是一个快速演示:

在 url http://www.mocky.io/v2/5583c7fe2dda051e04bc699a 上执行 GET 将 return 以下 json:

{
  data: [ ]
}

如果您 运行 以下 class,您会发现它运行良好:

public class RetrofitDemo {

  interface API {

    @GET("/5583c7fe2dda051e04bc699a")
    void getDataList(Callback<DataList> cb);
  }

  static class DataList {

    List<Data> data;
  }

  static class Data {
  }

  public static void main(String[] args) {

    API api = new RestAdapter.Builder()
        .setEndpoint("http://www.mocky.io/v2")
        .build()
        .create(API.class);

    api.getDataList(new Callback<DataList>() {

      @Override
      public void success(DataList dataList, Response response) {
        System.out.println("dataList=" + dataList);
      }

      @Override
      public void failure(RetrofitError retrofitError) {
        throw retrofitError;
      }
    });
  }
}