v5tech/notes

convert object/bean to map

v5tech opened this issue · 0 comments

Straight up Java

public void convert_object_to_map_introspector() throws IntrospectionException,
        IllegalAccessException, IllegalArgumentException,
        InvocationTargetException {

    Account account = new Account(1, "ameizi");

    Map<String, Object> objectAsMap = new HashMap<String, Object>();
    BeanInfo info = Introspector.getBeanInfo(account.getClass());
    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        Method reader = pd.getReadMethod();
        if (reader != null)
            objectAsMap.put(pd.getName(),reader.invoke(account));
    }
}

Apache Commons

public void convert_object_to_map_apache_commons() throws IllegalAccessException,
    InvocationTargetException, NoSuchMethodException {

    Account account = new Account(1, "ameizi");

    @SuppressWarnings("unchecked")
    Map<String, Object> objectAsMap = BeanUtils.describe(account);
}

Jackson

public void convert_object_to_map_jackson() {

    Account account = new Account(1, "ameizi");

    ObjectMapper objectMapper = new ObjectMapper();

    @SuppressWarnings("unchecked")
    Map<String, Object> objectAsMap = objectMapper.convertValue(account, Map.class);
}

https://www.leveluplunch.com/java/examples/convert-object-bean-properties-map-key-value