Convert Java Object to Map
You can use ObjectMapper.convertValue to convert a java object to a java map.
The convertValue method in the ObjectMapper class allows you to convert a Java object of one type to another type, without the need for explicit serialization and deserialization steps.
This method takes two parameters: the source object and the target type (specified as a JavaType or TypeReference).
Let’s consider a simple example to demonstrate the usage of convertValue. Suppose we have a Person class, and we want to convert an instance of Person to a Map<String, Object> representation:
@Data
static class Person {
private int age;
private String name;
private List<String> addresses;
}
@Test
public void testConvertObjectToMap() {
ObjectMapper mapper = new ObjectMapper();
Person person = new Person();
person.setName("John");
person.setAge(24);
person.setAddresses(Lists.newArrayList("1600 Amphitheatre Parkway", "Mountain View, CA 94043", "USA"));
// Convert Person to Map<String, Object>
Map<String, Object> personMap = mapper.convertValue(person, new TypeReference<Map<String, Object>>() {
});
Assertions.assertEquals(24, personMap.get("age"));
Assertions.assertEquals("John", personMap.get("name"));
Assertions.assertEquals(3, ((List<String>) personMap.get("addresses")).size());
}
In the above code, we first create an instance of ObjectMapper and a Person object. Then, using convertValue, we convert the Person object to a Map<String, Object>. The TypeReference is used to specify the target type, as the compiler cannot infer the type parameters from a raw Map class.
Besides, we can also use convertValue to convert an object to another java object, below is the example codes which converts a Person object to PersonVO object.
@Data
static class PersonVO {
private int age;
private String name;
private List<String> addresses;
}
@Test
public void testConvertObjectToObject() {
ObjectMapper mapper = new ObjectMapper();
Person person = new Person();
person.setName("John");
person.setAge(24);
person.setAddresses(Lists.newArrayList("1600 Amphitheatre Parkway", "Mountain View, CA 94043", "USA"));
PersonVO personVO = mapper.convertValue(person, PersonVO.class);
Assertions.assertEquals(24, personVO.getAge());
Assertions.assertEquals("John", personVO.getName());
Assertions.assertEquals(3, personVO.getAddresses().size());
}