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;//域名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>>() {});





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值