참고: http://www.leveluplunch.com/java/examples/convert-object-bean-properties-map-key-value/
Bean 데이터를 공통으로 받아서 Map 형태로 사용하고 싶을 때 유용하게 쓸 수 있다.
- 생 자바로
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"));
}
- 잭슨 형식
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"));
}
- Apach Common 이용
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"));
}
'Java & Spring > Java 문법' 카테고리의 다른 글
[Java] Jackson Json 파싱 예제 (0) | 2015.09.09 |
---|---|
[JAVA] Jackson을 이용한 Java JSON 파싱 (0) | 2015.09.09 |
URL Connection 이해와 예제 (0) | 2014.03.12 |
Java 1.8 업데이트, 뭐가 바뀌었나? (0) | 2013.10.28 |
자바 스터디 문제 2 (0) | 2013.07.18 |
WRITTEN BY