gson 提供方法 TypeToken<?> getParameterized(Type rawType, Type... typeArguments) 进行泛型转化:
- final Class<? super T> rawType; 基类信息
- final Type type; 底层反射实例
public static void main(String[] args) {
Map<String, Object> data1 = new HashMap<>();
data1.put("id", 11L);
data1.put("name", "dl");
data1.put("desc", "for test");
Map<String, Object> data2 = new HashMap<>();
data2.put("id", 112L);
data2.put("name", "dl2");
data2.put("desc", "for test2");
List<Map<String, Object>> dataList = new ArrayList<>();
dataList.add(data1);
dataList.add(data2);
Type type = TypeToken.getParameterized(List.class, Data.class).getType();
String json = new Gson().toJson(dataList);
List<Data> datas = new Gson().fromJson(json, type);
System.out.println(datas.toString());
}
@lombok.Data
private static class Data {
private Long id;
private String name;
private String desc;
}