Gson with generics - 如何使用内部泛型成员获取对象

时间:2014-05-20 21:50:24

标签: java json generics gson

我们说我有以下实体

public class City {
   public int id;
   public String name;
}

public class State<T> {
   public int id;
   public String name;

   public T capital;
}

我对资本类型一无所知。
现在我创建了两个对象并调用了json和fromJson,如下所示:

City capital = new City(1, "1");
State state = new State<City>(1, "1", capital);

Gson gson = new Gson();
String json = gson.toJson(state);
State fromJsonState = gson.fromJson(json, State.class);

我返回的from方法的对象是

enter image description here

所有内容都是键入的但是大写(通用)。
如何在json序列化之后获得相同的对象&amp; desirialize?

1 个答案:

答案 0 :(得分:0)

使用参数化TypeToken构建类型并使用Gson#fromJson(String,Type)

Gson gson = new Gson();
String json = gson.toJson(state);
Type type = new TypeToken<State<City>>() {}.getType();
State<City> fromJsonState = gson.fromJson(json, type); 

System.out.println(fromJsonState.capital.getClass().getName());

输出:

com.x.y.z.City