准备数据
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String account;
private String name;
private String password;
private String mobile;
}
第一种:使用Hutool工具
public class testClass {
public static void main(String[] args) {
User user = User.builder()
.account("001")
.name("张三")
.password("123456")
.mobile("12345678912")
.build();
System.out.println(user);//输出:User(account=001, name=张三, password=123456, mobile=12345678912)
//将对象转换为 Map
Map<String, Object> map = BeanUtil.beanToMap(user);
System.out.println(map);//输出:{account=001, name=张三, password=123456, mobile=12345678912}
//将map转换为 对象
User user1 = BeanUtil.toBean(map, User.class);
System.out.println(user1.getName());//输出:张三
// 使用CopyOptions自定义转换规则(name字段不进行转换)
CopyOptions options = CopyOptions.create();
options.setIgnoreProperties("name");
User user2 = BeanUtil.toBean(map, User.class, options);
System.out.println(user2);//输出:User(account=001, name=null, password=123456, mobile=12345678912)
}
}
第二种:使用 FastJosn
2.1 fastJson的TypeReference
FastJsonhttps://so.csdn.net/so/search?q=FastJson&spm=1001.2101.3001.7020
public class testClass {
public static void main(String[] args) {
User user = User.builder()
.account("001")
.name("张三")
.password("123456")
.mobile("12345678912")
.build();
System.out.println(user);//输出:User(account=001, name=张三, password=123456, mobile=12345678912)
//将对象user转化为map集合
userMap = JSON.parseObject(JSON.toJSONString(user), new TypeReference<>(){});
System.out.println(userMap.get("mobile"));//输出:12345678912
//将map集合转化为对象user1
User user1 = JSON.parseObject(JSON.toJSONString(userMap), new TypeReference<>(){});
System.out.println(user1.getName()); //输出:张三
}
}
2.2 通过Java对象和JSON之间的转换。
public class testClass {
public static void main(String[] args) {
User user = User.builder()
.account("001")
.name("张三")
.password("123456")
.mobile("12345678912")
.build();
System.out.println(user);//输出:User(account=001, name=张三, password=123456, mobile=12345678912)
//将对象user转化为map集合(var是JDK10新特性)
var map = JSON.parseObject(JSON.toJSONString(user), Map.class);
System.out.println(map);//输出:{password=123456, mobile=12345678912, name=张三, account=001}
//将map集合转化为对象user1
User user1 = JSON.parseObject(JSON.toJSONString(map), User.class);
System.out.println(user1);//输出:User(account=001, name=张三, password=123456, mobile=12345678912)
}
}
标签:map,实体类,name,mobile,User,集合,password,12345678912
From: https://blog.csdn.net/zxxCSDN_/article/details/139270224