Jackson ObjectMapper
- Java course
- Intermediate
- Lesson 76/116
- 5 min
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.
Practice 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.
Starter code
import com.fasterxml.jackson.databind.ObjectMapper;
// Define the User record
public class Main {
public static void main(String[] args) {
// Create ObjectMapper and User, two println calls
}
}Sample 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());
}
}Expected output
Ayşe ObjectMapper
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the main role of ObjectMapper?
- To connect to a database
- To convert between structured text and Java objects Correct answer
- To browse the file system
- To send HTTP requests
Explanation: ObjectMapper bridges structured text and Java objects.
2 Complete the ObjectMapper instance
ObjectMapper mapper = new ____();
ObjectMapper mapper = new ObjectMapper();
Explanation: The ObjectMapper instance is used for Jackson operations.
3 Match the Jackson concepts
| Term | Meaning |
|---|---|
ObjectMapper |
Central converter |
writeValueAsString |
Object to text |
readValue |
Text to object |
record |
Short data class |