Convert object/bean to map

This example will show how to convert a java object, bean or POJO to a map. The object properties will represent the map's keys while the properties value will represent the map's values. We will use straight up java, apache commons beanutils and jackson's objectMapper techniques.

Setup

public class NoteBook {
    
    private double numberOfSheets;
    private String description;

    public NoteBook(double numberOfSheets, String description) {
        super();
        this.numberOfSheets = numberOfSheets;
        this.description = description;
    }
    
    public double getNumberOfSheets() {
        return numberOfSheets;
    }
    public String getDescription() {
        return description;
    }
    
}

Straight up Java

@Test
public void convert_object_to_map_java() throws IntrospectionException,
        IllegalAccessException, IllegalArgumentException,
        InvocationTargetException {

    NoteBook actionMethodNoteBook = new NoteBook(100, "Action Method Notebook");

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

    assertThat(objectAsMap, hasEntry("numberOfSheets", (Object) new Double(100.0)));
    assertThat(objectAsMap, hasEntry("description", (Object) "Action Method Notebook"));
}

Apache Commons

@Test
public void convert_object_to_map_apache_commons () throws IllegalAccessException, 
    InvocationTargetException, NoSuchMethodException {
    
    NoteBook fieldNoteBook = new NoteBook(878, "Field Notebook");

    @SuppressWarnings("unchecked")
    Map<String, Object> objectAsMap = BeanUtils.describe(fieldNoteBook);
    
    assertThat(objectAsMap, hasEntry("numberOfSheets", (Object) "878.0"));
    assertThat(objectAsMap, hasEntry("description", (Object)  "Field Notebook"));
}

Jackson

@Test
public void convert_object_to_map_jackson () {
    
    NoteBook moleskineNoteBook = new NoteBook(200, "Moleskine Notebooks");
    
    ObjectMapper objectMapper = new ObjectMapper();
    
    @SuppressWarnings("unchecked")
    Map<String, Object> objectAsMap = objectMapper.convertValue(moleskineNoteBook, Map.class);
    
    assertThat(objectAsMap, hasEntry("numberOfSheets", (Object) new Double(200.0)));
    assertThat(objectAsMap, hasEntry("description", (Object) "Moleskine Notebooks"));
}