How to specify generic type in this case for GSON

Viewed 93

I have following code to illustrate my problem:

First, I define the Box class and Cat class

public class Box<T> {
    private T data;

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
public class Cat {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

Then I define the GsonUtils (static class) that aims to serialize some json string into an object of Box<T>

public class GsonUtils {

    public static <T> Box<T> json2BoxObject(String json) {
        Type tpe = new TypeToken<Box<T>>(){}.getType();
        return  new GsonBuilder().create().fromJson(json, tpe);
    }

}
  1. If I could provide a Cat type to json2BoxObject method, then I would get a Box<Cat>
  2. If I could provide a Dog Type to json2BoxObject method, then I would get a Box<Dog>

However, I don't know how to provide a type to json2BoxObject,this is the question I am asking

With the above code, give the json2BoxObject with json string {"data":{"name":"Kitty","age":1}}, I would like to get a Box<Cat> object, but I get a Box[Map]

1 Answers
Related