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 the Author

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

Comments

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
JussiAstaroth Recent comment authors
newest oldest most voted
Jussi
Guest
Jussi

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
Guest
Astaroth

Thanks!