How To Convert Map To Object In Java

Converting a Map to an Object in Java is a common programming task when working with data. A Map is a collection of key-value pairs, whereas an Object is a Java class instance with properties and methods.

In order to convert a Map to an Object, you need to define a Java class that matches the structure of the Map, and then populate its properties with the corresponding values from the Map.

One of the main reasons for converting a Map to an Object is to improve code readability and maintainability. By representing data as objects, you can access its properties in a more intuitive way, and leverage the power of object-oriented programming to encapsulate behavior and enforce data validation rules.

Why Converting Map To Object In Java is required

Converting a Map to an Object in Java can be useful for a variety of reasons, including:

  • Improved readability: Converting a Map to an Object, you may more easily access its properties, making the code more legible and understandable.
  • Type safety: The data types of the attributes and methods in the class when using objects rather than Maps, provides more safety.
  • Encapsulation: Encapsulating functionality and data validation criteria in objects, you may increase the modularity and maintainability of your code.
  • Abstraction: The level of abstraction offered for objects can be used for masking the implementation and making the code easier to read for end users.
  • Performance: The use of large datasets and retrieving properties directly from an object can be faster than getting them using a Map.
  • Refactoring: The use of simplified code refactoring and can help in preventing code duplication by converting Maps to objects.
  • Serialization: It is easy with which objects can be serialized and deserialized makes it possible to store and retrieve data from databases and transport data over networks.

Methods for Converting Map To Object In Java

There are several methods for converting a Map to an Object in Java, including:

  1. Manually mapping each property
  2. Reflection
  3. Jackson Object Mapper
  4. Gson
  5. Apache Commons BeanUtils

Let’s dive into each approach and learn with examples.

Approach 1: Using Manually mapping each property for Converting Map To Object In Java

You can manually create a new instance of the object, and set each property to the corresponding value from the Map. This method can be time-consuming and error-prone, but it gives you complete control over the mapping process.

Code:

import java.util.HashMap;
import java.util.Map;

public class User {
    private String name;    // Declare a private property 'name' of type String
    private int age;        // Declare a private property 'age' of type int
    private String email;   // Declare a private property 'email' of type String
    
    // Create a constructor that takes 'name', 'age' and 'email' as arguments and sets them
    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }
    
    // Create a getter method to retrieve the 'name' property
    public String getName() {
        return name;
    }
    
    // Create a getter method to retrieve the 'age' property
    public int getAge() {
        return age;
    }
    
    // Create a getter method to retrieve the 'email' property
    public String getEmail() {
        return email;
    }
    
    // Create a main method to test the User class
    public static void main(String[] args) {
        // Create a Map object and add the values of a user
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("name", "John Smith");
        userMap.put("age", 30);
        userMap.put("email", "[email protected]");
        
        // Create a new instance of the User class and pass in the values from the Map object
        User user = new User(
            (String) userMap.get("name"),    // Cast the 'name' property from Object to String
            (int) userMap.get("age"),        // Cast the 'age' property from Object to int
            (String) userMap.get("email")   // Cast the 'email' property from Object to String
        );
        
        // Print out the values of the properties using the getter methods
        System.out.println("Name: " + user.getName());
        System.out.println("Age: " + user.getAge());
        System.out.println("Email: " + user.getEmail());
    }
}

Output:

Name: John Smith
Age: 30
Email: [email protected]

Explanation of code:

  • We define a User class with three properties: name, age, and email.
  • We define a constructor that takes these three properties as arguments and sets them.
  • We define three getter methods to retrieve the values of these properties.
  • In the main method, we create a Map object with the values of the user.
  • We create a new instance of the User class, and pass in the values from the Map object.
  • We retrieve the values of the properties using the getter methods, and print them to the console.

Approach 2: Using Reflection for Converting Map To Object In Java

You can use Java’s reflection API to dynamically create an instance of the object, and set its properties based on the keys and values in the Map. This method can be more efficient than manual mapping, but it can also be more complex and harder to debug.

Code:

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class User {
    private String name;
    private int age;
    private String email;

    public User() {
    }

    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        // create a map with values for the object properties
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("name", "John Smith");
        userMap.put("age", 30);
        userMap.put("email", "[email protected]");

        // create a new instance of the User class using reflection
        User user = User.class.newInstance();

        // loop through each entry in the map and set the corresponding field in the User object
        for (Map.Entry<String, Object> entry : userMap.entrySet()) {
            Field field = getField(entry.getKey());
            if (field != null) {
                // make the field accessible (in case it is private)
                field.setAccessible(true);
                // set the value of the field in the User object to the value in the map
                field.set(user, entry.getValue());
            }
        }

        // print out the values of the User object properties
        System.out.println("Name: " + user.getName());
        System.out.println("Age: " + user.getAge());
        System.out.println("Email: " + user.getEmail());
    }

    // helper method to get the field with the given name from the User class
    private static Field getField(String fieldName) {
        try {
            return User.class.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            // if the field does not exist, return null
            return null;
        }
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getEmail() {
        return email;
    }
}

Output:

Name: John Smith
Age: 30
Email: [email protected]

Explanation of code:

  • We define the User class with three private fields – name, age, and email.
  • We define a default no-argument constructor and a constructor that takes the three fields as arguments.
  • In the main() method, we create a new HashMap and populate it with some sample data.
  • We then create a new instance of the User class using reflection. We use the newInstance() method on the User.class object to create a new instance of the class. This is equivalent to calling the no-argument constructor.
  • We then iterate over the entries in the Map, using the keys to look up

Approach 3: Using Jackson Object Mapper for Converting Map To Object In Java

Jackson is a popular Java library for working with JSON data, and it includes an ObjectMapper class that can be used to convert a Map to an Object. This method is very efficient and easy to use, but it requires that the keys in the Map match the property names in the Object.

Code:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

public class User {
    private String name;
    private int age;
    private String email;

    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getEmail() {
        return email;
    }

    public static void main(String[] args) throws Exception {
        // Create a Map object with user details
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("name", "John Smith");
        userMap.put("age", 30);
        userMap.put("email", "[email protected]");

        // Create an instance of ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        // Convert the Map to a User object
        User user = mapper.convertValue(userMap, User.class);

        // Print the details of the User object
        System.out.println("Name: " + user.getName());
        System.out.println("Age: " + user.getAge());
        System.out.println("Email: " + user.getEmail());
    }
}

Output:

Name: John Smith
Age: 30
Email: [email protected]

Explanation of code:

  • The ObjectMapper class is used to convert between Java objects and JSON (JavaScript Object Notation) data. It is part of the Jackson library.
  • In this approach, we create a Map object with the user details and then use the ObjectMapper to convert it into a User object.
  • The convertValue method of ObjectMapper is used to convert the Map object to a User object. It takes two arguments – the Map object and the class type of the object to be converted to.
  • The User class has a constructor that takes the name, age, and email as arguments. When the convertValue method is called, the ObjectMapper creates an instance of the User class and sets the values of its fields using the values from the Map object.
  • The getName, getAge, and getEmail methods are used to retrieve the values of the fields of the User object.

Dependency:

  • Download the Jackson library from https://github.com/FasterXML/jackson-core/releases
  • Extract the downloaded archive and locate the jar file for the core library (e.g., jackson-core-2.12.3.jar)
  • Add the jar file to the classpath of the project. This can be done by either adding it to the project’s build path or by specifying it in the command line when compiling and running the code.
  • The Jackson library is required for this approach. You can add the following dependency to your pom.xml file

Approach 4: Using Gson for Converting Map To Object In Java

Gson is another popular Java library for working with JSON data, and it includes a GsonBuilder class that can be used to convert a Map to an Object. This method is similar to the Jackson ObjectMapper, but it can handle more complex data types and nested objects.

Code:

import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;

public class User {
    private String name;
    private int age;
    private String email;

    public User() {
    }

    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    public static void main(String[] args) {
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("name", "John Smith");
        userMap.put("age", 30);
        userMap.put("email", "[email protected]");

        Gson gson = new Gson();
        User user = gson.fromJson(gson.toJson(userMap), User.class);

        System.out.println("Name: " + user.getName());
        System.out.println("Age: " + user.getAge());
        System.out.println("Email: " + user.getEmail());
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getEmail() {
        return email;
    }
}

Output:

Name: John Smith
Age: 30
Email: [email protected]

Explanation of code:

  • We create a new HashMap called userMap and add some properties to it.
  • We create a new instance of Gson.
  • We use the toJson() method to convert the map to a JSON string, and then pass that string to the fromJson() method along with the class of the object we want to parse it into.
  • We access the properties of the User object to verify that the conversion was successful.

Dependency:

  • Add Gson dependency to your project. Gson is a Java library that can be used to convert Java Objects into their JSON representation and vice versa. To add Gson to your project, add the following dependency to your pom.xml file if you’re using Maven:
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.8</version>
</dependency>
  • If you’re using Gradle, add the following line to your build.gradle file:
implementation 'com.google.code.gson:gson:2.8.8'
  • Create a Java class that represents the object we want to convert the map to. In this example, we’ll use the same User class as in the previous examples.
  • Create a Gson instance. Gson provides a convenient way to convert between Java objects and JSON strings. We can create a new instance of Gson by calling the Gson() constructor.
  • Use the fromJson() method to convert the map to the object. The fromJson() method takes two parameters: the JSON string to parse, and the class of the object to parse it into. In this case, we’ll convert the map to a User object.
  • Access the object’s properties to verify that the conversion was successful.

Approach 5: Using Apache Commons BeanUtils for Converting Map To Object In Java

The Apache Commons BeanUtils library includes a BeanUtils class that provides a variety of utility methods for working with Java beans, including a method for copying properties from a Map to an Object. This method is very flexible and can handle different data types and nested objects, but it can also be slower than other methods.

Code:

import org.apache.commons.beanutils.BeanUtils;
import java.util.HashMap;
import java.util.Map;

public class User {
    private String name;
    private int age;
    private String email;

    public User() {
    }

    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    public static void main(String[] args) throws Exception {
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("name", "John Smith");
        userMap.put("age", 30);
        userMap.put("email", "[email protected]");

        User user = new User();
        BeanUtils.populate(user, userMap); // Use BeanUtils to populate the User object with data from the map

        System.out.println("Name: " + user.getName());
        System.out.println("Age: " + user.getAge());
        System.out.println("Email: " + user.getEmail());
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getEmail() {
        return email;
    }
}

Output:

Name: John Smith
Age: 30
Email: [email protected]

Explanation of code:

  • We import the necessary classes from Apache Commons BeanUtils and Java’s standard library.
  • We define a User class with three properties: name, age, and email.
  • We define a default constructor and a constructor that takes three arguments for initializing the properties.
  • In the main method, we create a HashMap with the property names and values for a User object.
  • We create a new User object.
  • We call the BeanUtils.populate method to copy the values from the HashMap to the User object.
  • We print out the values of the User object’s properties.

Dependency:

To use Apache Commons BeanUtils, you need to add the following dependency to your pom.xml or build.gradle file:

Maven:

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Gradle:

implementation 'commons-beanutils:commons-beanutils:1.9.4'

Best Approach for Converting Map To Object In Java

Jackson Object Mapper is a popular library and here are some reasons why Jackson Object Mapper is considered the best approach for converting Map to Object in Java:

  • Easy to use: Jackson Object Mapper is easy to use, even for beginners. It provides simple and intuitive APIs for converting JSON data to Java objects.
  • High performance: Jackson Object Mapper is designed for high performance, making it suitable for large-scale applications. It uses efficient algorithms and optimized data structures to ensure fast conversion.
  • Flexible configuration: Jackson Object Mapper provides flexible configuration options, allowing developers to customize the mapping process according to their needs. For example, developers can configure the mapping behavior for specific fields, handle unknown properties, and more.
  • Supports different data formats: Jackson Object Mapper supports various data formats, including JSON, XML, YAML, and others. It also supports multiple Java data types, such as lists, maps, and custom objects.
  • Rich feature set: Jackson Object Mapper offers a rich feature set, including support for annotations, data binding, streaming API, and more. These features make it easier to map complex JSON data to Java objects.
  • Well-documented: Jackson Object Mapper is well-documented, with plenty of examples and tutorials available online. This makes it easy for developers to get started with the library and troubleshoot any issues they encounter.

Sample Problems for Converting Map To Object In Java

Sample Problem 1

Given a Map with variable keys and values, write a method that can dynamically map the keys and values to a POJO class with matching fields.

Solution:

  • Given a Map with variable keys and values, write a method that can dynamically map the keys and values to a POJO class with matching fields.
  • MapToPOJOConverter is a utility class that provides a static method named convert to convert a Map to a POJO class.
  • The method takes two parameters: a Map<String, Object> and a Class<T> representing the target POJO class to map the data to. The <T> is a type parameter indicating the target POJO class type.
  • The method first creates a new instance of the target POJO class using the newInstance method of the Class object. This requires the POJO class to have a default no-argument constructor.
  • It then iterates over each key-value pair in the input Map using a for loop.
  • For each key-value pair, it gets the corresponding field of the target POJO class using the getDeclaredField method of the Class object, passing the key as the field name. This method returns a Field object representing the field with the specified name in the target POJO class.
  • It then sets the field value of the target POJO instance using the set method of the Field object, passing the target POJO instance as the first argument and the value from the input Map as the second argument. The setAccessible method is called to allow the field to be accessed and modified even if it is private or protected.
  • Finally, the method returns the target POJO instance with the mapped data.

Implementation in Java using the Jackson library:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;

public class MapToPojoConverter {

    private final ObjectMapper objectMapper;

    public MapToPojoConverter() {
        this.objectMapper = new ObjectMapper();
    }

    public <T> T convert(Map<String, Object> map, Class<T> clazz) {
        return objectMapper.convertValue(map, clazz);
    }

}

This class uses the Jackson ObjectMapper to convert a Map<String, Object> to an instance of the specified POJO class:

import java.util.HashMap;
import java.util.Map;

public class ExampleUsage {

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "John Doe");
        map.put("age", 42);
        map.put("isStudent", false);

        MapToPojoConverter converter = new MapToPojoConverter();
        Person person = converter.convert(map, Person.class);

        System.out.println(person.getName()); // John Doe
        System.out.println(person.getAge()); // 42
        System.out.println(person.isStudent()); // false
    }

}

Output:

Name: John Smith
Age: 30
Email: [email protected]

Sample Problem 2

Write a method that takes in a Map and a Class type as arguments, and returns an instance of the given class with the fields populated based on the values in the Map. The method should use reflection to set the values of the fields.

Solution:

  • MapToPOJOConverter is a utility class that provides a static method named convert to convert a Map to a POJO class.
  • The method takes two parameters: a Map<String, Object> and a Class<T> representing the target POJO class to map the data to. The <T> is a type parameter indicating the target POJO class type.
  • The method first creates a new instance of the target POJO class using the getDeclaredConstructor method of the Class object. This requires the POJO class to have a default no-argument constructor.
  • It then iterates over each key-value pair in the input Map using a for loop.
  • For each key-value pair, it gets the corresponding field of the target POJO class using the getDeclaredField method of the Class object, passing the key as the field name. This method returns a Field object representing the field with the specified name in the target POJO class.
  • It then sets the field value of the target POJO instance using the set method of the Field object, passing the target POJO instance as the first argument and the value from the input Map as the second argument. The setAccessible method is called to allow the field to be accessed and modified even if it is private or protected.
  • Finally, the method returns the target POJO instance with the mapped data.
import java.lang.reflect.Field;
import java.util.Map;
public class MapToPOJOConverter {
    public static <T> T convert(Map<String, Object> map, Class<T> clazz) throws Exception {
        // Create a new instance of the target POJO class
        T instance = clazz.newInstance();        
        // Iterate over each key-value pair in the input map
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();            
            // Get the corresponding field of the target POJO class using reflection
            Field field = clazz.getDeclaredField(key);
            // Make the field accessible so that it can be modified
            field.setAccessible(true);   
            // Set the field value of the target POJO instance using reflection
            field.set(instance, value);
        }
               // Return the target POJO instance with the mapped data
        return instance;
    }
}

Output:

Name: John Smith
Age: 30
Email: [email protected]

Sample Problem 3

Given a JSON string that represents a Map with variable keys and values, write a method that can deserialize the JSON string into a POJO class with matching fields.

Solution:

  • The JsonDeserializer class defines a method deserialize that takes a JSON string and a class representing the target POJO as arguments, and returns an instance of the target POJO.
  • The constructor initializes an ObjectMapper object, which is used to convert between JSON and Java objects.
  • The deserialize method first defines a TypeReference object that describes the type of the Map that the JSON string will be deserialized into. In this case, the Map has String keys and Object values, which can represent any type of value.
  • The objectMapper object’s readValue method is used to deserialize the JSON string into a Map with the specified type reference.
  • The objectMapper object’s convertValue method is used to convert the Map into an instance of the target POJO class. This method uses reflection to set the values of the POJO’s fields based on the keys and values of the Map.
  • The deserialize method returns the resulting POJO instance.

A JSON string representing a Map into a POJO class with matching fields using the Jackson library:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

public class JsonDeserializer {
    private ObjectMapper objectMapper;

    public JsonDeserializer() {
        this.objectMapper = new ObjectMapper();
    }

    public <T> T deserialize(String json, Class<T> valueType) throws Exception {
        TypeReference<Map<String, Object>> mapTypeRef = new TypeReference<Map<String, Object>>() {};
        Map<String, Object> map = objectMapper.readValue(json, mapTypeRef);
        return objectMapper.convertValue(map, valueType);
    }
}

How to use the JsonDeserializer class:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        String json = "{\"name\":\"Alice\",\"age\":30}";
        JsonDeserializer deserializer = new JsonDeserializer();
        Person person = deserializer.deserialize(json, Person.class);
        System.out.println(person.getName()); // Alice
        System.out.println(person.getAge()); // 30
    }
}

Output:

Alice
30

Sample Problem 4

Given a JSON string that represents a Map with variable keys and values, write a method that can deserialize the JSON string into a POJO class with matching fields. The method should use GSon to perform the deserialization.

Solution:

  • The JsonDeserializer class defines a method deserialize that takes a JSON string and a Type representing the target POJO as arguments, and returns an instance of the target POJO.
  • The constructor initializes a Gson object, which is used to convert between JSON and Java objects.
  • The deserialize method first deserializes the JSON string into a Map using the fromJson method of the gson object. The type of the Map’s values is Object, which can represent any type of value.
  • The gson object’s toJson method is used to serialize the Map back into JSON, and then the fromJson method is used again to deserialize the JSON into an instance of the target POJO type. This method uses reflection to set the values of the POJO’s fields based on the keys and values of the Map.
  • The deserialize method returns the resulting POJO instance.

In Java that deserializes a JSON string representing a Map into a POJO class with matching fields using the Gson library:

import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.Map;

public class JsonDeserializer {
    private Gson gson;

    public JsonDeserializer() {
        this.gson = new Gson();
    }

    public <T> T deserialize(String json, Type type) {
        Map<String, Object> map = gson.fromJson(json, Map.class);
        return gson.fromJson(gson.toJson(map), type);
    }
}

How to use the JsonDeserializer class:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        String json = "{\"name\":\"John\",\"age\":51}";
        JsonDeserializer deserializer = new JsonDeserializer();
        Type type = new TypeToken<Person>() {}.getType();
        Person person = deserializer.deserialize(json, type);
        System.out.println(person.getName()); // John
        System.out.println(person.getAge()); // 51
    }
}

Output:

John
51

Sample Problem 5

Given a Map with variable keys and values, write a method that can populate an existing POJO object with matching fields based on the values in the Map. The method should use Apache Commons BeanUtils to set the values of the fields.

Solution:

  • The PojoPopulator class defines a static method populate that takes an existing POJO object and a Map representing the property values as arguments, and sets the values of the POJO’s fields based on the values in the Map.
  • The method uses a for-each loop to iterate over the entries in the Map.
  • For each entry, the method gets the property name and value and passes them to the setProperty method of the BeanUtils class, which sets the value of the property on the given object using reflection.
  • The populate method throws two checked exceptions, IllegalAccessException and InvocationTargetException, which are declared in its signature. These exceptions can occur if the Java security manager forbids access to the property or if the property setter throws an exception, respectively. The calling code should handle these exceptions appropriately.
  • The populate method is declared as static, so it can be called without creating an instance of the PojoPopulator class.

In Java that populates an existing POJO object with matching fields based on a Map using the BeanUtils library from Apache Commons:

import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class PojoPopulator {
    public static void populate(Object pojo, Map<String, ?> map)
            throws IllegalAccessException, InvocationTargetException {
        for (Map.Entry<String, ?> entry : map.entrySet()) {
            String propertyName = entry.getKey();
            Object value = entry.getValue();
            BeanUtils.setProperty(pojo, propertyName, value);
        }
    }
}

How to use the PojoPopulator class:

public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "Johnson");
        map.put("age", 45);
        Person person = new Person();
        PojoPopulator.populate(person, map);
        System.out.println(person.getName()); // Johnson
        System.out.println(person.getAge()); // 45
    }
}

Output:

Johnson
45

Conclusion

In conclusion, there are multiple methods for converting a Map to an Object in Java. This depends on unique requirements of the use case, either strategy may be adopted because both have advantages of their own. Gson offers a straightforward method for converting a JSON string to a POJO, whereas BeanUtils offers a more versatile and potent method for adding values from a Map to an existing object.