Java
Jackson ObjectMapper
Learn to produce JSON from objects with Jackson ObjectMapper.
Jackson ObjectMapper
The Jackson library converts Java objects to structured text and back. Its central class is ObjectMapper. You create an instance with ObjectMapper mapper = new ObjectMapper();. To convert an object to text use mapper.writeValueAsString(obj); to parse text into an object use mapper.readValue(text, User.class).
A simple record or POJO automatically uses its field names as keys. Jackson works with canonical constructors, accessors or records. In this lesson we first define a User record and create an ObjectMapper instance.
Data model with record
Since Java 16, record defines short data classes. The line record User(String name, int age) {} auto-generates a constructor, accessors, equals, hashCode and toString. Jackson supports records directly.
Record fields are final; they have no mutator methods. This makes them ideal for immutable data models. Jackson matches fields automatically from the record constructor.
Exercise User record and ObjectMapper
Define record User(String name, int age) {}. In main, create an ObjectMapper mapper = new ObjectMapper();, create a user with User u = new User("Ayşe", 30);, and print the name with System.out.println(u.name());. Also print the class name of the mapper with System.out.println(mapper.getClass().getSimpleName()); to confirm it is in use.
Show example solution
import com.fasterxml.jackson.databind.ObjectMapper;
record User(String name, int age) {}
public class Main {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
User u = new User("Ayşe", 30);
System.out.println(u.name());
System.out.println(mapper.getClass().getSimpleName());
}
}
Test yourself
-
What is the main role of ObjectMapper?
- To connect to a database
- To convert between structured text and Java objects
- To browse the file system
- To send HTTP requests
Show answer
To convert between structured text and Java objects — ObjectMapper bridges structured text and Java objects.
-
Complete the ObjectMapper instance
ObjectMapper mapper = new ____();
Show answer
ObjectMapper mapper = new ObjectMapper();
-
Match the Jackson concepts
- ObjectMapper
- Central converter
- writeValueAsString
- Object to text
- readValue
- Text to object
- record
- Short data class
Next lesson: readValue