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

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.

Leave a Comment