Java introspection: object to map
Another way to user JacksonObjectMapper
is the convertValue
ex:
ObjectMapper m = new ObjectMapper();
Map<String,Object> mappedObject = m.convertValue(myObject, new TypeReference<Map<String, String>>() {});
You can use JavaBeans introspection for this. Read up on the java.beans.Introspector
class:
public static Map<String, Object> introspect(Object obj) throws Exception {
Map<String, Object> result = new HashMap<String, Object>();
BeanInfo info = Introspector.getBeanInfo(obj.getClass());
for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
Method reader = pd.getReadMethod();
if (reader != null)
result.put(pd.getName(), reader.invoke(obj));
}
return result;
}
Big caveat: My code deals with getter methods only; it will not find naked fields. For fields, see highlycaffeinated's answer. :-) (You will probably want to combine the two approaches.)
Use Apache Commons BeanUtils: http://commons.apache.org/beanutils/.
An implementation of Map for JavaBeans which uses introspection to get and put properties in the bean:
Map<Object, Object> introspected = new org.apache.commons.beanutils.BeanMap(object);
Note: despite the fact the API returns Map<Object, Object>
(since 1.9.0), the actual class for keys in the returned map is java.lang.String