Sometimes, we may need to convert the java objet to key-value pairs, for example Map or Properties class. It can be doable in multiple ways like using reflection or jackson library. We are going to use jackson library to achieve it here.
Annotation processor to generate DTO class from Entity class
Entity to DTO conversion using jackson
Maven dependency
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.9</version> </dependency>
Employee.java
We will use this class to convert to map and properties class.class Employee{ private long id; private String name; private Integer age; public Employee(long id, String name, Integer age) { super(); this.id = id; this.name = name; this.age = age; } //getter methods //setter methods }
Generic method to convert the object
Jackson library provides ObjectMapper class which provides "convertValue" method to convert the java objects. Below is the code for our generic method which accepts the object to be converted and class to which it will convert the object.public <T> T convertObjToMap(Object o, TypeReference<T> ref) { ObjectMapper mapper = new ObjectMapper(); return mapper.convertValue(o, ref); }
Execute the convert method
Below code will execute two scenarios, one to convert to Map and another to convert to Properties class.//Create java object to be converted Employee emp = new Employee(6L, "Emp-1", 30); //Convert to Map<String, String> class Map<String, String> map = convertObjToMap(emp, new TypeReference<Map<String, String>>(){}); System.out.println("Convert to Map<String, String> :"); System.out.println(map); //Convert to Properties class Properties props = convertObjToMap(emp, new TypeReference<Properties>(){}); System.out.println("\nConvert to Properties :"); System.out.println(props);
Output:
Below is the output of above code executionConvert to MapOther links you may be interested in:: {id=6, name=Emp-1, age=30} Convert to Properties : {age=30, name=Emp-1, id=6}
Annotation processor to generate DTO class from Entity class
Entity to DTO conversion using jackson
Comments
Post a Comment