0
点赞
收藏
分享

微信扫一扫

FastJson的typeReference使用场景

史值拥 2022-02-15 阅读 68


​​原文​​

当我们需要反序列化一个 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());
}



举报

相关推荐

0 条评论