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.


public class NoteBook {

    private double numberOfSheets;
    private String description;

    public NoteBook(double numberOfSheets, String description) {
        this.numberOfSheets = numberOfSheets;
        this.description = description;

    public double getNumberOfSheets() {
        return numberOfSheets;
    public String getDescription() {
        return description;


Straight up Java

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)

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

Apache Commons

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

    NoteBook fieldNoteBook = new NoteBook(878, "Field Notebook");

    Map<String, Object> objectAsMap = BeanUtils.describe(fieldNoteBook);

    assertThat(objectAsMap, hasEntry("numberOfSheets", (Object) "878.0"));
    assertThat(objectAsMap, hasEntry("description", (Object)  "Field Notebook"));


public void convert_object_to_map_jackson () {

    NoteBook moleskineNoteBook = new NoteBook(200, "Moleskine Notebooks");

    ObjectMapper objectMapper = new ObjectMapper();

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

Convert object/bean to map posted by Justin Musgrove on 15 December 2013

Tagged: java and java-general

============ 我说2句: 最后我选择用jackson. 因为BeanUtils.describe方法会解出"class":"类名",而且只会解出getProperty()方法对应的属性,对于public属性不会解出。