How to map one object to another in java

What you will learn here about java

  • How to map one object to another in java

How to map one object to another in java

Please follow the following steps to know how to map one object to another in java.
1)First Create simple maven project

2)Add maven maven dependency of jackson in your pom.xml which is shown below
maven Jackson dependency

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

3)Now to POJO classes for your objects which you want to convert from one to another which is shown below
java object mapping
one object to another object conversion in java

4)Its very easy to convert one object to another object using ObjectMapper which is shown below
How to map one object to another in java

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MainApp {

    public static void main(String[] args) {
        UserDetails userDetails = new UserDetails();
        userDetails.setFirstName("John");
        userDetails.setLastName("Dow");
        userDetails.setDob("29/02/1995");
        userDetails.setCollegeName("MIT");
        userDetails.setPlace("Pune");
        userDetails.setPinCode(564321);
        
        PersonalInfo personInfo = (PersonalInfo) objectMapper(userDetails);
        System.out.println("First name : "+ personInfo.getFirstName());
        System.out.println("Last name : "+ personInfo.getLastName());
        System.out.println("DOB : "+ personInfo.getDob());
        
        
    }

    public static Object objectMapper(Object object){
    	ObjectMapper mapper = new ObjectMapper();
    	mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    	PersonalInfo personInfo = mapper.convertValue(object, PersonalInfo.class);
        return personInfo;
    }
}

5)Now Please run the code. Once you run the code you see following kind of output on the console which is shown below
java map one object to another

You may also like...