准备
导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
创建User类
创建UserDto类
对象互转(将User转为UserDto)
User u = new User("1","小王",18);
String jsonString = JSONObject.toJSONString(u);
UserDto userDto = JSONObject.parseObject(jsonString, UserDto.class);
Map转对象(将Map转为UserDto)
Map<String,Object> userMap = new HashMap<>();
userMap.put("id","2");
userMap.put("name","小刘");
userMap.put("age",19);
String jsonStringMap = JSONObject.toJSONString(userMap);
UserDto dto = JSONObject.parseObject(jsonStringMap, UserDto.class);
对象转Map(将User转为Map)
User u = new User("1","小王",18);
String jsonString = JSONObject.toJSONString(u);
Map map = JSONObject.parseObject(jsonString, Map.class);
可以看到上边不管是如何转换,其实只用了两个方法,toJSONString和parseObject,另外使用JSON对象也可以实现同样的效果,如下
Map<String,Object> userMap = new HashMap<>();
userMap.put("id","2");
userMap.put("name","小刘");
userMap.put("age",19);
String s = JSON.toJSONString(userMap);
User user = JSON.parseObject(s, User.class); //User(id=2, name=小刘, age=19)
对象填充
如果项目中使用了spring那么可以使用BeanUtils工具
UserDto userDto = new UserDto();
userDto.setId("1");
userDto.setName("piper");
userDto.setAge(18);
User user = new User();
user.setId("2");
user.setName("小王");
user.setAge(19);
BeanUtils.copyProperties(userDto, user);
System.out.println(userDto.toString()); //UserDto(id=1, name=piper, age=18)
System.out.println(user.toString()); //User(id=1, name=piper, age=18)