【泛型】Gson的序列化和反序列化

數據結構

public class Pagination<T> {
    private T data;
}
class Person{
    private String name;
    private int age;

    public Person(){}
    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}


方法

    public static String toGson(Object obj){
        return new Gson().toJson(obj, new TypeToken<Paginate<Person>>(){}.getType());
    }

    public static String toGson(Object obj){
        Gson gson = new Gson();
        Type objectType = getType(Paginate.class, Person.class);
        return gson.toJson(obj, objectType);
    }

    public static String toGson(Paginate obj){
        return new Gson().toJson(obj, getTypeToken(obj.getData().getClass()).getType());
    }

工具方法

    public static <T> com.google.common.reflect.TypeToken<Paginate<T>> getTypeToken(Class<T> recordClass) {
        return new com.google.common.reflect.TypeToken<Paginate<T>>(){}.where(new TypeParameter<T>() {}, recordClass);
    }

public static Type getType(final Class raw, final Type... args){
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }

            public Type[] getActualTypeArguments() {
                return args;
            }

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章