1

Are there any mapping libraries (like Dozer) which can map from a Map<String, Object> to a pojo/bean?

My specific use case is to map ScriptObjectMirrors coming out of nashorn, but I should be able to work at a higher interface since ScriptObjectMirror implements Map.

kag0
  • 5,624
  • 7
  • 34
  • 67
  • That wouldn't be hard to make. Of course you would have to define the target classes yourself. – Jorn Vernee Aug 11 '16 at 17:42
  • @JornVernee the library or a manual mapping? Either way is easy but manual mapping is labor intensive and most existing libraries have advanced features which would be tedious to implement, and test myself, especially if there is something already out there. – kag0 Aug 11 '16 at 17:47

2 Answers2

2

While not exactly a duplicate, I found this question provides a straightforward answer.

In essence, Jackson's ObjectMapper can be used for object-to-object mapping in addition to its commonly known JSON ability. The below code shows how this can easily be done in two lines.

final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);
Community
  • 1
  • 1
kag0
  • 5,624
  • 7
  • 34
  • 67
1

You can use orika mapper. It is very flexible and extendable. You can find more details here.

Please read through the user guide.

It's also mentioned in the FAQ.

Can I map an object contained in a collection or map to a field, or vice-versa

Yes. (as of version 1.3.0) For a Bean to Map, simply define your class-map as normal using the mapperFactory.classMap(...) method, passing one of the types as a Class (or Type) which is assignable to java.util.Map. The field-names on the Map side of the equation will be used as the Map keys.

Using the byDefault() method in such a scenario would result in all the properties of the Bean type being mapped by their property name into the Map type.

For a Bean to List or Array, follow the same strategy as mentioned above for Maps, but instead of providing key values, you would instead provide index values within the Array or List at which the Bean values should be stored.

kag0
  • 5,624
  • 7
  • 34
  • 67
Guenther
  • 2,035
  • 2
  • 15
  • 20