Java — Convert Object to Map example
1 min readMay 30, 2019
In Java, you can use the Jackson library to convert a Java object into a Map
easily.
1. Get Jackson
pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
2. Convert Object to Map
2.1 A Jackson 2 example to convert a Student
object into a java.util.Map
Student.java
package com.nayan.examples;import java.util.List;public class Student { private String name;
private int age;
private List<String> skills; // getters setters
}
ObjectToMapExample.java
package com.nayan.examples;import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Arrays;
import java.util.Map;public class ObjectToMapExample { public static void main(String[] args) { ObjectMapper oMapper = new ObjectMapper(); Student obj = new Student();
obj.setName("nayan");
obj.setAge(34);
obj.setSkills(Arrays.asList("java","angular")); // object -> Map
Map<String, Object> map = oMapper.convertValue(obj, Map.class);
System.out.println(map); }}
Output
{name=nayan, age=34, skills=[java, angular]}