Programming
Converting POJO to Map and vice versa with Jackson
A quick look at how to convert a POJO from/to a
Map<K,V>
with Jackson:
// Create ObjectMapper instance
ObjectMapper mapper = new ObjectMapper();
// Converting 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, the convertValue()
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.