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

后端 未结 2 441
孤街浪徒
孤街浪徒 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 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 map = 
        mapper.convertValue(foo, new TypeReference>() {});
    
    // 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.

提交回复
热议问题