赞
踩
//模拟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<User> list = JSONArray.toList(JSONArray.fromObject(code, User.class);
使用com.alibaba.fastjson.JSON;
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.9</version>
</dependency>
案例使用
//code是集合字符串
List<User> list = JSON.parseArray(code, User.class);
指定泛型直接转List<T>:
- //引入的包分别是:
- import com.fasterxml.jackson.core.type.TypeReference;
- import com.fasterxml.jackson.databind.ObjectMapper;
-
-
- ObjectMapper mapper = new ObjectMapper();
- List list = xxx.getXxx();
- List<User> users = mapper.convertValue(list, new TypeReference<List<User>>() { });
使用方法一存在问题:转实体的属性必须与目标实体一一对应,局限
使用方法二:转实体属性不需要与目标实体一一对应,实体有的字段就会对应上,没有的不会报错
推荐使用二
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。