實戰中常需在 Map、Java Bean (Object)、JSON 之間轉換。本文匯總三種 Map↔Object 轉換方案(Apache BeanUtils、Introspector、反射)及 Jackson 實現 Map↔JSON 轉換。
class A {
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null) return null;
Object obj = beanClass.newInstance();
org.apache.commons.beanutils.BeanUtils.populate(obj, map);
return obj;
}
public static Map<?, ?> objectToMap(Object obj) {
if (obj == null) return null;
return new org.apache.commons.beanutils.BeanMap(obj);
}
}
class B {
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null) return null;
Object obj = beanClass.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
Method setter = pd.getWriteMethod();
if (setter != null) setter.invoke(obj, map.get(pd.getName()));
}
return obj;
}
public static Map<String, Object> objectToMap(Object obj) throws Exception {
if (obj == null) return null;
Map<String, Object> map = new HashMap<>();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String key = pd.getName();
if ("class".equalsIgnoreCase(key)) continue;
Method getter = pd.getReadMethod();
Object value = getter != null ? getter.invoke(obj) : null;
map.put(key, value);
}
return map;
}
}
class C {
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null) return null;
Object obj = beanClass.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) continue;
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
return obj;
}
public static Map<String, Object> objectToMap(Object obj) throws Exception {
if (obj == null) return null;
Map<String, Object> map = new HashMap<>();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
}
}
Map<String, Object> map = new HashMap<>();
map.put("method", "json");
map.put("param", null);
map.put("time", "2015-01-23 10:54:55");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
public static void readJson2Map(String json) {
ObjectMapper objectMapper = new ObjectMapper();
try {
Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
System.out.println(maps.size());
for (String key : maps.keySet()) {
System.out.println(key + ":" + maps.get(key));
}
} catch (Exception e) { e.printStackTrace(); }
}