Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.Document -> json -> POJO.

I am using gson to convert POJO to json,

Gson gson = new GsonBuilder().create(); String json = gson.toJson(pojo); 

then

Document doc = Document.parse(json);  

to create the document and it is easy. But other way around is problematic. document.toJson() is not giving standard json for long, timestamp etc and gson is complaining while deserialising to POJO. So I need a way to convert org.bson.Document to standard json.

NOTE: I want to avoid using mongo java driver or morphia as this work does not relate to mongo in anyway.

like image 928
Anindya Chatterjee Avatar asked Sep 17 '16 07:09

Anindya Chatterjee


People also ask

How do you turn a POJO object into a map?

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.

Can we convert map to set Java?

You can not convert Java Map to Java Set.


2 Answers

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.

like image 200
cassiomolin Avatar answered Sep 22 '22 01:09

cassiomolin


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

like image 34
Gregor Avatar answered Sep 21 '22 01:09

Gregor