原文
当我们需要反序列化一个 m a p map map时
public static void main(String[] args) {
Map<String, Person> map = new HashMap<>(16);
map.put("one", new Person("zhangsan"));
map.put("two", new Person("lisi"));
String jsonStr = JSON.toJSONString(map);
byte[] bytes = jsonStr.getBytes();
String json = new String(bytes);
Map<String, Person> res = JSON.parseObject(json, Map.class);
System.out.println(res.get("one"));
System.out.println(res.get("one").getName());
}
这样写会报错,因为在JSON.parseObject
只传入了Map.class
,并不会解析为对象Person
的形式
这个时候可以使用typeReference
public static void main(String[] args) {
Map<String, Person> map = new HashMap<>(16);
map.put("one", new Person("zhangsan"));
map.put("two", new Person("lisi"));
String jsonStr = JSON.toJSONString(map);
byte[] bytes = jsonStr.getBytes();
String json = new String(bytes);
Map<String, Person> res = JSON.parseObject(json, new TypeReference<Map<String, Person>>(){});
System.out.println(res.get("one"));
System.out.println(res.get("one").getName());
}