Java Jackson ObjectMapper Class with Examples


Post Banner

The ObjectMapper class from the com.fasterxml.jackson.databind is the class that can be used to convert Java Objects (mostly POJOs) to JSON and vice-versa.

To make use of the ObjectMapper, you will need to add the jackson-databind dependency in your Gradle/Maven Project,

How to add Jackson Dependecy in Gralde Project

How to add Jackson Dependecy in Maven Project



Example: ObjectMapper to convert JSON String to Java Object

Employee.java
public class Employee {

    String empName;
    int empAge;
    String empDept;

    public  Employee() {}
    
    public Employee(String empName, int empAge, String empDept) {
        this.empName = empName;
        this.empAge = empAge;
        this.empDept = empDept;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public int getEmpAge() {
        return empAge;
    }

    public void setEmpAge(int empAge) {
        this.empAge = empAge;
    }

    public String getEmpDept() {
        return empDept;
    }

    public void setEmpDept(String empDept) {
        this.empDept = empDept;
    }
}
import com.fasterxml.jackson.databind.ObjectMapper;

public class ObjectMapperExample {

    public static void main(String[] args) {

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String employeeJson = "{ \"empName\" : \"Jake\", \"empAge\" : 35, \"empDept\" : \"Insurance\"}";

            Employee employee = objectMapper.readValue(employeeJson, Employee.class);
            System.out.println("Employee Name:" + employee.getEmpName());
            System.out.println("Employee Department:" + employee.getEmpDept());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Example: ObjectMapper to convert Java Object to Json String

    public static void main(String[] args) {

        try {
            Employee employee = new Employee("Jake",45,"Finance");
            ObjectMapper objectMapper = new ObjectMapper();
            String employeeJsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
            System.out.println("Employee Json :" + employeeJsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
Output:
Employee Json :{
  "empName" : "Jake",
  "empAge" : 45,
  "empDept" : "Finance"
}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap