當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JSON转List
JSON轉List在平時的開發中經常遇到,這里介紹兩張方法:
1.使用jackson(推薦,支持嵌套復雜結構):
ObjectMapper mapper = new ObjectMapper(); JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, MachineConnectResultVO.class); List<MachineConnectResultVO> resMsg = new ArrayList<MachineConnectResultVO>(); try {resMsg = (List<MachineConnectResultVO>)mapper.readValue(res, javaType); } catch (IOException e) {e.printStackTrace(); }
2.使用JsonArray:
JSONArray idsArr = JSONArray.fromObject(idStr); List<DomainKeepOption> domainKeepOptionList = JSONArray.toList(idsArr, new DomainKeepOption(), new JsonConfig());
上面的XX.class可以是你自己定義的復雜VO,需要你提前按照JSON的格式構造好
public class MachineConnectResultVO {private String assetNum;private List<IpConnectVO> ips;getters and setters... } public class IpConnectVO {private String ip;private Boolean status;getter and setter... } public class DomainKeepOption {private Integer id;//域名idprivate Integer keepA;//1選中 0未選中private Integer keepHaiWai;//1選中 0未選中getter and setter... }有點要注意的是jsonArray這種形式不支持嵌套復雜類型的如上面的MachineConnectResultVO下又有IpConnectVO這個類型,jackson對這個支持的很好
而且jackson方法還可以用下面這個方式試下(沒測試過),更加簡潔明了
ObjectMapper mapper = new ObjectMapper(); List<MachineConnectResultVO> aa = mapper.readValue(res, new TypeReference<List<MachineConnectResultVO>>() {});
總結
- 上一篇: 【机器学习】GitHub 标星17.4K
- 下一篇: 【机器学习】使用 Python 构建电影