Java ObjectMapper explained

Priya Salvi
2 min readApr 21, 2024

--

In Java, an object mapper is a tool used to convert data between incompatible type systems, such as converting objects to and from database rows, JSON documents, or XML files. It’s commonly used in applications where you need to translate data between different representations, like from a database to a Java object or vice versa.

One of the most popular object mapping libraries in Java is Jackson. Jackson provides powerful features for converting Java objects to and from JSON (JavaScript Object Notation), which is widely used for data interchange in web applications.

Here’s how you can use Jackson’s ObjectMapper in Java with a real-time example:

Let’s say you have a Java class representing a Person:

public class Person {
private String name;
private int age;

// Getters and setters
// Constructor
// Other methods
}

Now, suppose you have JSON data representing a person:

{
"name": "John",
"age": 30
}

You can use Jackson’s ObjectMapper to convert this JSON data into a Person object:

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
public static void main(String[] args) {
String json = "{\"name\":\"John\",\"age\":30}";

try {
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(json, Person.class);

System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
} catch (Exception e) {
e.printStackTrace();
}
}
}

In this example, we use the readValue() method of ObjectMapper to convert the JSON string into a Person object. Jackson automatically maps the fields in the JSON to the corresponding fields in the Person class.

Similarly, you can use ObjectMapper to convert a Java object into JSON:

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
public static void main(String[] args) {
try {
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person("Alice", 25);
String json = objectMapper.writeValueAsString(person);

System.out.println("JSON: " + json);
} catch (Exception e) {
e.printStackTrace();
}
}
}

In this example, we use the writeValueAsString() method of ObjectMapper to convert the Person object into a JSON string.

So, in summary, ObjectMapper from Jackson is a powerful tool for converting between Java objects and JSON, enabling seamless data interchange in Java applications.

--

--

Priya Salvi

Software Engineer | Oracle Certified Java Associate | Neophile | Bibliophile