public static Map<String,Object> beanToMap(Object object){
Map<String,Object> map = null;
try {
map = new HashMap<String, Object>();
BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (key.compareToIgnoreCase("class") == 0) {
continue;
}
Method getter = property.getReadMethod();
Object value = getter!=null ? getter.invoke(object) : null;
map.put(key, value);
}
//key 可能會把自己的class 和hashcode編進去,直接去掉
map.remove("class");
} catch (Exception e) {
e.printStackTrace();
return new HashMap<>();
}
Set<String> set = map.keySet();
Iterator<String> it = set.iterator();
while (it.hasNext()){
String key = it.next();
if (map.get(key)==null || map.get(key)==""){
map.remove(key);
set = map.keySet();
it = set.iterator();
}
}
return map;
}
java 對象轉map,去掉null
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.