简体   繁体   中英

Casting a parameterized type to a class for Gson

I am using LoopJ on android to get Http responses. What i want to do is pass my own types and return responses of that type. Here is a single country model

class Country:BaseModel() {

    @PrimaryKey
    @SerializedName("id")
    var id: Int=0

    @Column
    @SerializedName("name")
    var name: String? = null

    @Column
    @SerializedName("code")
    var code: String? = null

    @SerializedName("country_code")
    @Column
    var country_code: String? = null
}

The class i made to serialize a Json array to objects using Gson is as follows

public class LoopGsonResponseHandler<T> extends JsonHttpResponseHandler {

    public T Model;


    //Prototype to handle the Gson list of objects
    public void onSuccess(int statusCode, Header[] headers, T single){
    }

    //Prototype to handle the Gson list of objects
    public void onSuccess(int statusCode, Header[] headers, ArrayList<T> list){
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
        super.onSuccess(statusCode, headers, response);
        //call on succecc with parameter 3 being model
        Type collectionType = new TypeToken<T>(){}.getType();
        T data = new Gson().fromJson(response.toString(), collectionType);
        this.onSuccess(statusCode,headers,data);
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
        super.onSuccess(statusCode, headers, response);
        //call on succecc with parameter 3 being list
        Log.e("Country","We got array");

        Type collectionType = new TypeToken<ArrayList<T>>(){}.getType();
        ArrayList<T> data = new Gson().fromJson(response.toString(), collectionType);
        this.onSuccess(statusCode,headers,data);
    }
}

I successfully parse the response to gson objects but i cannot parse them to the parameterized types. The error i get is this

 java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.neverest.client.models.MyJson
         at com.neverest.client.utils.LoopGsonResponseHandler.onSuccess(LoopGsonResponseHandler.java:34)
         at com.neverest.client.utils.LoopGsonResponseHandler.onSuccess(LoopGsonResponseHandler.java:55)
         at com.loopj.android.http.JsonHttpResponseHandler$1$1.run(JsonHttpResponseHandler.java:154)

Pass in the class using the constructor like this

public class LoopGsonResponseHandler<T> extends JsonHttpResponseHandler{

    public T model;

    private final Class<T> classOfT;

    public LoopGsonResponseHandler(Class<T> classOfT){
        this.classOfT = classOfT;
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response){
        super.onSuccess(statusCode, headers, response);

        T data = new Gson().fromJson(response.toString(), classOfT);
        this.onSuccess(statusCode, headers, data);
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
        super.onSuccess(statusCode, headers, response);
        //call on succecc with parameter 3 being list
        Log.e("Country","We got array");

        Type collectionType = new ListParametrizedType(classOfT);
        ArrayList<T> data = new Gson().fromJson(response.toString(), collectionType);
        this.onSuccess(statusCode,headers,data);
    }
}

Then make the LoopGsonResponseHandler object like this.

new LoopGsonResponseHandler(Country.class);

For the ArrayList, you will need this class

private static class ListParametrizedType implements ParameterizedType {

        private Type type;

        public ListParametrizedType(Type type) {
            this.type = type;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{type};
        }

        @Override
        public Type getRawType() {
            return ArrayList.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }

        @Override
        public boolean equals(Object obj) {
            return super.equals(obj);
        }
    }

And you are done. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM