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;//域名id
private 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>>() {});
本文介绍了两种将JSON转换为List的方法:一是使用jackson,它支持复杂的嵌套结构;二是利用JsonArray,适用于简单结构。同时对比了两种方法的特点,并提供代码示例。
2223

被折叠的 条评论
为什么被折叠?



