java bean中包含list<object>转
2017-05-13 本文已影响438人
武小寺
public static Map<String, Object> javabeanToMap(Object bean) {
Map<String, Object> result = new HashMap<String, Object>();
if (bean == null) {
return result;
}
Field[] fields = bean.getClass().getDeclaredFields();
if (fields == null || fields.length == 0) {
return result;
}
for (Field field : fields) {
// 重置属性可见(而且一般属性都是私有的),否则操作无效
boolean accessible = field.isAccessible();
if (!accessible) {
field.setAccessible(true);
}
String key = field.getName();
try {
// 获取子类属性
Object value = field.get(bean);
if (value instanceof java.util.List) {
List list = (List) value;
List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
Object obj;
for (int i = 0; i < list.size(); i++) {
obj = list.get(i);
// list里是map或String,不会存在list里直接是list的,
Field[] fieldChilds = obj.getClass().getDeclaredFields();
Map<String, Object> resultChild = new HashMap<String, Object>();
for (Field field2 : fieldChilds) {
// 重置属性可见(而且一般属性都是私有的),否则操作无效
boolean accessible2 = field2.isAccessible();
if (!accessible2) {
field2.setAccessible(true);
}
try {
// 获取属性名称及值存入Map
String key1 = field2.getName();
Object ooo = field2.get(obj);
System.out.println("==key " + key1 + ";;;;;" + ooo);
resultChild.put(key1, field2.get(obj));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IllegalAccessException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
// 还原属性标识
field.setAccessible(accessible2);
}
mapList.add(resultChild);
}
result.put(key, mapList);
} else {
result.put(key, field.get(bean));
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
// 还原属性标识
field.setAccessible(accessible);
}
// 获取父类属性
fields = bean.getClass().getSuperclass().getDeclaredFields();
if (fields == null || fields.length == 0) {
return result;
}
for (Field field : fields) {
// 重置属性可见(而且一般属性都是私有的),否则操作无效
boolean accessible = field.isAccessible();
if (!accessible) {
field.setAccessible(true);
}
// 获取属性名称及值存入Map
String key = field.getName();
try {
result.put(key, field.get(bean));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
// 还原属性标识
field.setAccessible(accessible);
}
return result;
}