Main Tutorials

Java – Convert Object to Map example

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.mkyong.examples;

import java.util.List;

public class Student {

    private String name;
    private int age;
    private List<String> skills;

    // getters setters
}
ObjectToMapExample.java

package com.mkyong.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("mkyong");
        obj.setAge(34);
        obj.setSkills(Arrays.asList("java","node"));

        // object -> Map
        Map<String, Object> map = oMapper.convertValue(obj, Map.class);
        System.out.println(map);

    }

}

Output


{name=mkyong, age=34, skills=[java, node]}

References

  1. Jackson 2 – How to convert object to JSON
  2. Jackson @Github
  3. Jackson Home

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Jussi
6 years ago

Note that it is better to use TypeReference instead of a direct class in this case as the second rgument to convertValue(). This way we have a checked assignment to correctly typed map instead of Map.

oMapper.convertValue(obj, new TypeReference<Map<String, Object>>() {});

Astaroth
6 years ago

Thanks!

sidabw
2 years ago

Thanks +1

manikandan
1 year ago

when try on this -> Map map = oMapper.convertValue(obj, Map.class);
It show {empty:false }.. Kindly reslove this.