punksta
punksta

Reputation: 2808

Retrofit parse empty array []

I need to parse list of object, whith can be emply. {"data":[]} I use tamplated callback CallBack<T>called with

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

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

it crashed with error:java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com...DataList Please help

Upvotes: 1

Views: 690

Answers (2)

Bart Kiers
Bart Kiers

Reputation: 170148

Your model should work fine. Perhaps your server isn't returning what you think it does, or maybe its not application/json what it's returning?

Here's a quick demo:

Doing a GET on the url http://www.mocky.io/v2/5583c7fe2dda051e04bc699a will return the following json:

{
  data: [ ]
}

If you run the following class, you'll see it works just fine:

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

Upvotes: 1

JakeWilson801
JakeWilson801

Reputation: 1036

Your issue is your java model doesn't reflect the data it's trying to deserialize to.

//{"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;
}

Upvotes: 0

Related Questions