Convert object/bean to map

方健發表於2015-04-14

http://www.leveluplunch.com/java/examples/convert-object-bean-properties-map-key-value/
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"));
}

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屬性不會解出。

相關文章