- The Techno Journals
- Maven dependency
- Employee.java
- Generic method to convert the object
- Execute the convert method
- Output:
- Labels
- Comments
- Post a Comment
- Popular Posts
- Setting up kerberos in Mac OS X
- SpringBoot — @ConditionalOnProperty example for conditional bean initialization
- Spring Batch tutorial with example
- Multiple data source with Spring boot, batch and cloud task
- Convert an Object to Map in Java
- How to Convert Object to Map in Java
- How to convert object to HashMap in Java
The Techno Journals
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.
Maven dependency
com.fasterxml.jackson.core jackson-databind 2.9.9
Employee.java
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 convertObjToMap(Object o, TypeReference 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 class Map map = convertObjToMap(emp, new TypeReference
Output:
Convert to Map : Convert to Properties : Annotation processor to generate DTO class from Entity class
Entity to DTO conversion using jackson
- Get link
- Other Apps
Labels
- Get link
- Other Apps
Comments
Post a Comment
Popular Posts
Setting up kerberos in Mac OS X
Kerberos in MAC OS X Kerberos authentication allows the computers in same domain network to authenticate certain services with prompting the user for credentials. MAC OS X comes with Heimdal Kerberos which is an alternate implementation of the kerberos and uses LDAP as identity management database. Here we are going to learn how to setup a kerberos on MAC OS X which we will configure latter in our application. Installing Kerberos In MAC we can use Homebrew for installing any software package. Homebrew makes it very easy to install the kerberos by just executing a simple command as given below. brew install krb5 Once installation is complete, we need to set the below export commands in user’s profile which will make the kerberos utility commands and compiler available to execute from anywhere. Open user’s bash profile: vi ~/.bash_profile Add below lines: export PATH=/usr/local/opt/krb5/bin:$PATH export PATH=/usr/local/opt/krb5/sbin:$PATH export LDFLAGS=&
- Get link
- Other Apps
SpringBoot — @ConditionalOnProperty example for conditional bean initialization
@ConditionalOnProperty annotation is used to check if specified property available in the environment or it matches some specific value so it can control the execution of some part of code like bean creation. It may be useful in many cases for example enable/disable service if specific property is available. Below are the attributes which can be used for property check. havingValue — Provide the value which need to check against specified property otherwise it will check that value should not be false. matchIfMissing — If true it will match the condition and execute the annotated code when property itself is not available in environment. name — Name of the property to be tested. If you want to test single property then you can directly put the property name as string like «property.name» and if you have multiple properties to test then you can put the names like <"prop.name1","prop.name2">prefix — It can be use when you want to apply some prefix to"prop.name1","prop.name2">
- Get link
- Other Apps
Spring Batch tutorial with example
Spring batch is used to create and process the batch jobs. It provides various features like logging, job statistics, transaction management, restarting jobs. It is very helpful in processing of large dataset but with finite volume of data. In this tutorial we will learn how to create and execute the spring batch job. In our example we will create a job which will import all the words from a text file to database and then at last it will print the total number of words available in the database. Below is the project structure. Creating batch job Sample text file to import Below is the contents of text file which we use for importing the words. The list below gives you the 1000 most frequently used English words in alphabetical order. Once you’ve mastered the shorter vocabulary lists, this is the next step. It would take time to learn the entire list from scratch, but you are probably already familiar with some of these words. Feel free to copy this list into
- Get link
- Other Apps
Multiple data source with Spring boot, batch and cloud task
Here we will see how we can configure different datasource for application and batch. By default, Spring batch stores the job details and execution details in database. If separate data source is not configured for spring batch then it will use the available data source in your application if configured and create batch related tables there. Which may be the unwanted burden on application database and we would like to configure separate database for spring batch. To overcome this situation we will configure the different datasource for spring batch using in-memory database, since we don’t want to store batch job details permanently. Other thing is the configuration of spring cloud task in case of multiple datasource and it must point to the same data source which is pointed by spring batch. In below sections, we will se how to configure application, batch and cloud task related data sources. Application Data Source Define the data source in application properties or yml con
- Get link
- Other Apps
Convert an Object to Map in Java
Learn to convert an Object to a Java Map using different ways provided by Jackson and Gson APIs. It is also possible to use create your own solution using Java reflection, but it is not recommended to reinvent the wheel until the provided solutions do not serve your purpose.
In this tutorial, we will convert an instance of the following Employee class into a Map. The Employee class has simple types such as String, and new Java types such as LocalDate and Collection types.
We have a List of Role types to further demonstrate the behavior of different solutions. We will see how different solutions convert the nested types in the converted Map.
class Employee < private Integer id; private String name; private LocalDate dateOfBirth; private Listlocations; private List roles; > class Role
Jackson is a multi-purpose library that supports different types of conversions such as JSON or XML very well. Jackson also supports converting an Object to Map using the following ways:
2.1. Using ObjectMapper.convertValue()
The convertValue() method does two-step conversion from a given value into an instance of the given value type. It first serializes the given value into JSON and then binds JSON data into the value of the given type. But the conversion is more efficient since full serialization does not (need to) occur.
Note that in the following example we are registering the JavaTimeModule class because Jackson does not support new Java 8 Date-time classes, by default.
Employee employee = new Employee(1, "Alex", LocalDate.of(1995, 1, 2), List.of("Delhi", "Nevada"), List.of(new Role(11, "Finance"), new Role(12, "HR"))); System.out.println(convertObjectToMapUsingObjectMapper(employee)); //The conversion method static Map convertObjectToMapUsingObjectMapper(Employee employee)
Note that this method converts the associated and nested classes (such as Role) also into LinkedHashMap.
2.2. Using JavaPropsMapper to Convert to Properties
Another interesting solution is to convert the Object to Properties. Properties have a flat structure. Even the nested structures and collections convert into flat structure and all fields/values are converted into String. It may be a good solution in some cases.
Employee employee = new Employee(1, "Alex", LocalDate.of(1995, 1, 2), List.of("Delhi", "Nevada"), List.of(new Role(11, "Finance"), new Role(12, "HR"))); System.out.println(convertObjectToMapUsingJavaPropsMapper(employee)); //The conversion method static Properties convertObjectToMapUsingJavaPropsMapper(Employee employee) throws IOException
Let us check out the object hierarchy in the debugger.
If our project is already having Gson dependency in the application, we can consider using Gson.fromJson() to convert object to JSON and the converting the JSON to HashMap in the second step.
This technique uses full serialization and deserialization, so it may not give a better performance than Jackson. Use Gson when using Jackson is not possible for some reason.
Employee employee = new Employee(1, "Alex", LocalDate.of(1995, 1, 2), List.of("Delhi", "Nevada"), List.of(new Role(11, "Finance"), new Role(12, "HR"))); System.out.println(convertObjectToMapUsingGson(employee)); static Map convertObjectToMapUsingGson(Employee employee) < Gson gson = new GsonBuilder() .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) .create(); return gson.fromJson(gson.toJson(employee), new TypeToken>() < >.getType() ); >
There are primarily two differences between conversion using Gson and Jackson.
- Gson, by default, converts all number values to Double type.
- Gson uses LinkedTreeMap for nested classes in place of LinkedHashMap used by Jackson.
Another possible method, though not recommended, is reflection. Using reflection, we must write all the logic by ourselves, and thus there are chances of errors. If you adopt this approach, make sure to test it well before deploying it into production.
The following is a very basic snippet for a simple POJO class that relies on getting the value of a field by its name. We can tweak the method to fetch the value by its getter if there is such a requirement.
public static Map toKeyValuePairs(Object instance) < return Arrays.stream(Employee.class.getDeclaredFields()) .collect(Collectors.toMap( Field::getName, field -> < try < Object result = null; field.setAccessible(true); result = field.get(instance); return result != null ? result : ""; >catch (Exception e) < return ""; >>)); >
We can verify the map structure in the next diagram. It has the nested classes untouched because we are not accessing them or processing them in our logic. If you need to process them in your application then further expand the logic in toKeyValuePairs() method.
This Java tutorial taught us to convert a given Java object into a Map using different solutions. By looking at all solutions, Jackson seems the best solution in terms of ease and performance and is recommended approach in most cases.
For creating flat structures, we can convert Object to Properties using JavaPropsMapper.
Using Gson is quite similar to Jackson, but it does not provide any additional benefit, rather all numbers are converted to Double which may not a desirable situation in some cases. So use it when you cannot use Jackson.
Finally, reflection gives total control into your hand, and you must write every possible usecase/condition yourself.
How to Convert Object to Map in Java
In this Java tutorial, we learn how to implement a Java utility class to convert an object to a Map object in Java programming language.
How to convert object to HashMap in Java
At this first step, create a new Java class named MapUtils, implement a static method named toMap(Object value) with the following steps to convert object to Map:
- Create a new HashMap object as a result of method.
- Use the Object.getClass().getDeclaredFields() method to get the Field[] array.
- Loop through the Field[] array, each item use Field.getName() and Field.get(Object obj) method to get the field name and value to put to the result HashMap
import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class MapUtils /** * This method to convert an object to a Map * @param value the Object to convert * @return the Map result */ public static Map toMap(Object value) MapObject, Object> result = new HashMap<>(); Field[] fields = value.getClass().getDeclaredFields(); for(Field field : fields) try field.setAccessible(true); result.put(field.getName(), field.get(value)); > catch (IllegalAccessException e) e.printStackTrace(); > > return result; > >
For example, we have a Java class named Contact as below.
public class Contact private String firstName; private String lastName; private String email; public String getFirstName() return firstName; > public void setFirstName(String firstName) this.firstName = firstName; > public String getLastName() return lastName; > public void setLastName(String lastName) this.lastName = lastName; > public String getEmail() return email; > public void setEmail(String email) this.email = email; > >
In the following example Java code, we learn how to convert a Contact object to a HashMap in Java program.
import java.util.Map; public class MapUtilsExample public static void main(String. args) Contact contact = new Contact(); contact.setFirstName("Simple"); contact.setLastName("Solution"); contact.setEmail("contact@simplesolution.dev"); // Convert Object to Map Map map = MapUtils.toMap(contact); System.out.println(map); > >