How to specify the generic type in this case for GSON
I have the following code to illustrate my problem:
First I define 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 a GsonUtils
(static class) whose purpose is to serialize some json string into an objectBox<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 specify the type
Cat
for the methodjson2BoxObject
, then I would getBox<Cat>
- If I could provide a
Dog
Type to methodjson2BoxObject
, then I would getBox<Dog>
However I do not know how to provide the type json2BoxObject
, this is the question I am asking
With the above code give json2BoxObject
with a json string {"data":{"name":"Kitty","age":1}}
, I would like to get an object Box<Cat>
, but I get Box [Map]
source to share
You need to mention Cat or Dog at some point. I created a Type using Box and passed it in a method json2Java
.
String msg ="{\"data\":{\"name\":\"Kitty\",\"age\":1}}";
Type type = new TypeToken<Box<Cat>>(){}.getType();
Box<Cat> obj = GsonUtils.json2Java(msg, type);
System.out.println(obj);
And the json2Java
method:
public static <T> Box<T> json2Java(String json, Type type) {
Box<T> box = new GsonBuilder().create().fromJson(json, type);
return box;
}
source to share