当需要把map转为实体对象时,需要结合fastjson来实现,方法如下:
LinkedHashMap<String,Object> hashMap = new LinkedHashMap<>(); hashMap.put("name", "张三"); hashMap.put("age", 20); hashMap.put("addr", "湖北武汉1号"); User user = JSON.parseObject(JSON.toJSONString(hashMap), User.class);
User实体对象:
import lombok.Data;
@Data
public class User {
private String name;
private String addr;
private Integer age;
}
同理当需要把一个存有LinkedHashMap的集合转成存放对象的集合时,方法如下:
List<Map> list1 = new ArrayList<>(); for (int i = 1; i <= 5; i++) { LinkedHashMap<Object, Object> hashMap = new LinkedHashMap<>(); hashMap.put("name", "张三" + i); hashMap.put("age", 20 + i); hashMap.put("addr", "湖北武汉" + i + "号"); list1.add(hashMap); } //转数组对象 List<User> userList = JSON.parseArray(JSON.toJSONString(list1), User.class);