How to convert POJO to Map and vice versa in Java?

后端 未结 2 440
孤街浪徒
孤街浪徒 2020-12-01 08:14

My use case is to convert any arbitrary POJO to Map and back from Map to POJO. So I ended up using the strategy POJO -> json -> org.bson.Document and back to org.bson.Docume

相关标签:
2条回答
  • 2020-12-01 08:57

    even simpler, you can use PropertyUtils.describe(Object o)

    0 讨论(0)
  • 2020-12-01 09:05

    My use case is to convert any arbitrary POJO to Map and back from Map to POJO.

    You could use Jackson, a popular JSON parser for Java:

    ObjectMapper mapper = new ObjectMapper();
    
    // Convert POJO to Map
    Map<String, Object> map = 
        mapper.convertValue(foo, new TypeReference<Map<String, Object>>() {});
    
    // Convert Map to POJO
    Foo anotherFoo = mapper.convertValue(map, Foo.class);
    

    According to the Jackson documentation, this method is functionally similar to first serializing given value into JSON, and then binding JSON data into value of given type, but should be more efficient since full serialization does not (need to) occur. However, same converters (serializers and deserializers) will be used as for data binding, meaning same object mapper configuration works.

    0 讨论(0)
提交回复
热议问题