使用jackson-databind
可以将JavaBean对象属性转换为Map集合。
添加配置依赖:
代码语言:javascript复制<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
转换示例:
代码语言:javascript复制// 使用jackson将JavaBean对象属性转换为Map集合
public class JavaBeanToMapTest {
public static void main(String[] args) {
Subject subject = new Subject();
subject.setId(10);
subject.setName("Test");
subject.setAddr("Beijing");
Map<String, Object> map = new ObjectMapper().convertValue(subject, new TypeReference<Map<String, Object>>() {});
// 输出:{id=10, name=Test, addr=Beijing}
System.out.println(map);
// 不转换null值
subject.setAddr(null);
map = new ObjectMapper().convertValue(subject, new TypeReference<Map<String, Object>>() {});
// 输出:{id=10, name=Test}
System.out.println(map);
}
static class Subject {
Integer id;
String name;
// 如果希望null值不被转换,需要使用注解标注为Include.NON_NULL
String addr;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}
}