How to Convert Object to Map in Java

Convert Object to Map in Java

In this example, we will show you simple program about, How to Convert Object to Map in Java. The example program has been tested and shared in the post.

Maven Dependency

<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.3</version>
</dependency>

POJO Class (Customer.java)

package com.dineshkrish;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class Customer {

	private int id;
	private String name;
	private int age;
	private String address;
	private String phone;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	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 String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

}

Converting to Object to Map (Converter.java)

 
package com.dineshkrish;

import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class Converter {

	public static void main(String[] args) {

		ObjectMapper objectMapper = new ObjectMapper();

		Customer customer = new Customer();

		customer.setId(101);
		customer.setName("Dinesh");
		customer.setAge(20);
		customer.setPhone("1234567890");
		customer.setAddress("India");

		Map<String, String> map = objectMapper.convertValue(customer, Map.class);

		System.out.println(map);

	}

}

Output

{id=101, name=Dinesh, age=20, address=India, phone=1234567890}

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.