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);
}
}
- If I could provide a
Cattype tojson2BoxObjectmethod, then I would get aBox<Cat> - If I could provide a
DogType tojson2BoxObjectmethod, then I would get aBox<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]