java 对象转map,去掉null
时间: 2024-06-13 08:05:01 浏览: 76
Desktop_javaBean转换Map工具_
可以使用Java中的BeanUtils和MapUtils类来实现对象转map的功能,并使用迭代器遍历map,去掉值为null的键值对。具体代码如下所示:
```java
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.MapUtils;
public static Map<String, Object> beanToMap(Object object) {
Map<String, Object> map = null;
try {
map = BeanUtils.describe(object);
map.remove("class");
map.remove("hashCode");
map.remove("toString");
map.remove("equals");
} catch (Exception e) {
e.printStackTrace();
return new HashMap<>();
}
Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> entry = it.next();
if (entry.getValue() == null) {
it.remove();
}
}
return map;
}
```
阅读全文