java 集合反序列化

417 阅读1分钟

在一次项目开发中,需要将一个字符串反序列转成map,简化来看是这样的

Map<String, String> map = new HashMap<>();
map.put("hello", "world");
String mapStr = new Gson().toJson(map);
new Gson().fromJson(mapStr, new TypeToken<Map<String, String>>() {}.getType());

从上面的代码可以看出,在反序列化的时候是用了泛型。但是在项目中是通过反射拿到的class信息,所以这种方式在项目中是行不通的。 在通过查询资料后发现,有一个是通过class类型的方式来反序列化

ObjectMapper mapper= new ObjectMapper();
MapType type = mapper.getTypeFactory().constructMapType(HashMap.class, class1, class2);
Map dataMap = mapper.readValue(str, type);

类似的问题在集合中也存在 例如

List<String> list = Lists.newArrayList("hello", "world");
String listStr = new Gson().toJson(list);
List<String> toList = new Gson().fromJson(listStr, new TypeToken<List<String>>() {}.getType());
ObjectMapper mapper= new ObjectMapper();
CollectionLikeType type = mapper.getTypeFactory().constructCollectionLikeType(List.class, String.class);
List<String> toList = mapper.readValue(listStr, type);