码迷,mamicode.com
首页 > Web开发 > 详细

fastJson转List<实体>

时间:2020-02-22 19:51:38      阅读:547      评论:0      收藏:0      [点我收藏+]

标签:enc   hashmap   sharp   额外   api   fas   解决方案   需要   type   

问题

当我们用 fastjson 如下 API 转成 List<T> 这种类型时,会遇到类型丢失的问题

 

com.alibaba.fastjson.JSON#parseObject(java.lang.String, java.lang.Class<T>)

  

解决方案

String testJSON = "[{\"type\":\"a\"},{\"type\":\"b\"}]";
List<Button> buttons = JSON.parseObject(testJSON, new TypeReference<ArrayList<Button>>() {});

  

 

或者还有一种更通用的转换方式

 

List<Button> buttons = JSON.parseArray(testJSON, Button.class);

  

更多

同理,这种同样可以解决 Map 的问题

 
String testMapJSON = "{\"1\":{\"type\":\"a\"},\"2\":{\"type\":\"b\"}}";
Map<String, Button> buttonMap = JSON.parseObject(testMapJSON, new TypeReference<HashMap<String, Button>>() {});

  

如果是嵌套层次中属性有接口或父类型的,JSON 实际类型需要额外 @type 属性来指定当前类型,并且要放到 JSON 类字符串的第一行。




fastJson转List<实体>

标签:enc   hashmap   sharp   额外   api   fas   解决方案   需要   type   

原文地址:https://www.cnblogs.com/achengmu/p/12346694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!