json格式字符串的list集合转list对象集合

方法一

//模拟json格式集合字符串

String code = "[{"age":0,"jid":"0","name":"0"},{"age":1,"jid":"1","name":"1"},{"age":2,"jid":"2","name":"2"},{"age":3,"jid":"3","name":"3"},{"age":4,"jid":"4","name":"4"},{"age":5,"jid":"5","name":"5"},{"age":6,"jid":"6","name":"6"},{"age":7,"jid":"7","name":"7"},{"age":8,"jid":"8","name":"8"},{"age":9,"jid":"9","name":"9"}]";

//转对象集合

List list = JSONArray.toList(JSONArray.fromObject(code, User.class);

方法二(推荐使用)

使用com.alibaba.fastjson.JSON; 

com.alibaba

fastjson

1.2.9

案例使用

//code是集合字符串

List list = JSON.parseArray(code, User.class);

指定泛型直接转List:

//引入的包分别是:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; 


ObjectMapper mapper = new ObjectMapper();
 List list = xxx.getXxx();
 List users = mapper.convertValue(list, new TypeReference>() { });

总结

使用方法一存在问题:转实体的属性必须与目标实体一一对应,局限

使用方法二:转实体属性不需要与目标实体一一对应,实体有的字段就会对应上,没有的不会报错

推荐使用二

你可能感兴趣的:(数据结构,json,list)