Image of Java – Convert Object to Map

ADVERTISEMENT

Introduction

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:

private void convertObjToMapReflection()
{
    Map<String, Object> studentMap = new HashMap<String,Object>();
    Student student = new Student();
    student.setId(1);
    student.setName("Terek");
        
    Field[] allFields = student.getClass().getDeclaredFields();
    for (Field field : allFields) {
        field.setAccessible(true);
        Object value = field.get(student);
        studentMap.put(field.getName(), value);
    } 
    System.out.println(studentMap);
}

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.

private void convertObjToMapJackson()
{
    ObjectMapper oMapper = new ObjectMapper();
 
    Student student = new Student();
    student.setId(1);
    student.setName("Terek");
 
    Map<String, Object> studentMap = oMapper.convertValue(student, Map.class);
        
    System.out.println(studentMap);
}

Summary

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

Next Steps

If you're interested in learning more about the basics of Java, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.