Java – Convert Object to Map

This tutorial provides several ways of converting a Java object to a Map in Java.

1. Reflection

The traditional way of converting a Java object to a Map is through using the reflection mechanism provided by the JDK.

Suppose we have a class called Student that holds 2 fields id and name. The following method converts the Student object to a Map<String, Object> using reflection:

2. Jackson

The other way of doing the conversion is through using Jackson library.

The following example uses the same example above for converting a Student object to Map<String, Object> using Jackson library.

3.5 4 votes
Article Rating

Hussein Terek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ravi
Ravi
4 months ago

Exception in thread “main” java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/exc/InputCoercionException
 at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.createMapDeserializer(BasicDeserializerFactory.java:1376)
 at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:384)
 at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:349)
 at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
 at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
 at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
 at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:476)
 at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:4389)
 at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3915)
 at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3853)
 at com.test.json.ConvObjectToMap.main(ConvObjectToMap.java:17)
Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.core.exc.InputCoercionException
 at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
 … 11 more
Process finished with exit code 1