Convert Java Object to Map
Published in
2 min readMay 5, 2023
Scenario
Need to convert a simple java object having some attributes or properties and need to convert its values into a Map.
Solution
There are many solutions but the easiest solution (and my personal preference) is by using the Jackson library dependency.
Use this dependency in your pom.xml file
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.0</version>
</dependency>
Lets define a class to which will be converted into the Map.
Java Class — Employee Class
class Employee {
String name;
Integer age;
List<String> skills;
// getter setter methods
}
Now you can write a function to convert the java object into a Map.
import java.util.Arrays;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
public class FooBar {
public static convertObjectToMap(Employee employee) {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map= mapper.convertValue(employee, Employee.class);
return map;
}
}
Example
class Main {
public static void main(String[] args){
Employee emp = new Employee();
emp.setName("ABC");
emp.setAge(30);
emp.setSkillts(Arrays.asList("hello", "there"));
// object --> map
Map<String, Object> objectMap = FooBar.convertObjectToMap(emp);
System.out.println(obejctMap);
}
}
Output
{
name : "ABC",
age : 30,
skills : [
"hello",
"there"
]
}
Bonus
You can create a generic function which can convert any object to a map
public static convertObjectToMap(T object) {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map= mapper.convertValue(object, T.class);
return map;
}
Now you can reuse this function to convert any object into a map.