首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Map 與 Object、JSON 互轉完整實戰指南

     編輯:Java 相關知識

Java Map 與 Object、JSON 互轉完整實戰指南

實戰中常需在 Map、Java Bean (Object)、JSON 之間轉換。本文匯總三種 Map↔Object 轉換方案(Apache BeanUtils、Introspector、反射)及 Jackson 實現 Map↔JSON 轉換。

方案一:Apache Commons BeanUtils

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);
    }
}

方案二:Introspector (Java 標準 API)

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 ⇄ JSON (Jackson)

Map 轉 JSON 字串

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);

JSON 字串轉 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(); }
}

方案選型建議

  • BeanUtils:代碼最簡潔,需引入 commons-beanutils 依賴。
  • Introspector:零依賴,標準 API,效能較好。
  • 反射:可訪問 private 字段,但需處理修飾符,效能最差。
  • Jackson:JSON 處理首選,效能強、功能全。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved