Moshi: java.lang.ClassCastException: com.squareup.moshi.LinkedHashTreeMap cannot be cast to ...

Created on 16 Jan 2017  路  4Comments  路  Source: square/moshi

I have the method:

public PaginationData<T> call(String response) {
    try {
        Log.d(TAG, "call: " + response);
        Moshi moshi = new Moshi.Builder().build();
        Type type = Types.newParameterizedType(PaginationData.class, Object.class);
        JsonAdapter<PaginationData<T>> adapter = moshi.adapter(type);
        return adapter.fromJson(response);
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }
}

PaginationData:

class PaginationData<T>
{
    @Json(name = "total")
    public int total;
    @Json(name = "per_page")
    public int perPage;
    @Json(name = "current_page")
    public int currentPage;
    @Json(name = "last_page")
    public int lastPage;
    @Json(name = "next_page_url")
    public String nextPageUrl;
    @Json(name = "prev_page_url")
    public String prevPageUrl;
    @Json(name = "from")
    public int from;
    @Json(name = "to")
    public int to;
    @Json(name = "data")
    public List<T> data;
}

How can I specify the type for a list?

When I try to get the item from list I get the error:
java.lang.ClassCastException: com.squareup.moshi.LinkedHashTreeMap cannot be cast to ...

Most helpful comment

I got rid of the error by specifying the correct parameter class:
Type type = Types.newParameterizedType(PaginationData.class, User.class);
小an not do without it?

All 4 comments

I got rid of the error by specifying the correct parameter class:
Type type = Types.newParameterizedType(PaginationData.class, User.class);
小an not do without it?

It'd be impossible to guess what T is.

This makes performance on the app to really cringe, when you have a complex generic type, where you have to convert the LinkedHashTreeMap to Json first then back to the Type you want it to return. Because am experiencing the same issue, when T is null, it returns a LinkedHashTreeMap, when it has a value it returns T, which seems odd.

@schatzdesigns I don't really understand where that flow could happen in Moshi. As mentioned in the other issue - please post on stackoverflow with the Moshi tag and full code samples if you're having usage issues. This issue tracker is not the appropriate place for those. Comments like the above with missing context are not very constructive and make it difficult for anyone to help.

Was this page helpful?
0 / 5 - 0 ratings