ObjectMapper: object to JSON and back
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every REST endpoint turns a Java object into JSON for the client and turns the client's JSON back into an object. Writing that by hand for every class would be slow and full of mistakes.
One shared, thread-safe JsonMapper
Thread-safe code can be used by many threads at the same time without locks or wrong results. A Jackson 3 JsonMapper is immutable, so one shared mapper can serve every request.
One static final mapper is built once and used by many threads. The program below converts three books in parallel with it.
Example 1 · SharedMapperDemo.java: one mapper, many threads
Runs in: the json-playground Maven project with Jackson 3.1.5
import java.math.BigDecimal;import java.util.List;import tools.jackson.databind.SerializationFeature;import tools.jackson.databind.json.JsonMapper;
public class SharedMapperDemo {
// Built once when the class loads, then shared by every method and every thread static final JsonMapper MAPPER = JsonMapper.builder().build();
static class Product { private final String sku; private final String name; private final BigDecimal price;
Product(String sku, String name, BigDecimal price) { this.sku = sku; this.name = name; this.price = price; }
public String getSku() { return sku; } public String getName() { return name; } public BigDecimal getPrice() { return price; } }
public static void main(String[] args) { List<Product> products = List.of( new Product("BK-CLEAN", "Clean Code", new BigDecimal("499.00")), new Product("BK-PRAG", "The Pragmatic Programmer", new BigDecimal("650.00")), new Product("BK-ATOMIC", "Atomic Habits", new BigDecimal("399.00")));
// parallelStream() does the work on several threads at once; one mapper serves them all List<String> lines = products.parallelStream() .map(MAPPER::writeValueAsString) .toList(); lines.forEach(System.out::println);
// A Jackson 3 mapper never changes after build(); rebuild() makes a configured copy JsonMapper pretty = MAPPER.rebuild().enable(SerializationFeature.INDENT_OUTPUT).build(); System.out.println("Shared mapper indents: " + MAPPER.isEnabled(SerializationFeature.INDENT_OUTPUT)); System.out.println("Copy indents: " + pretty.isEnabled(SerializationFeature.INDENT_OUTPUT)); }}{"name":"Clean Code","price":499.00,"sku":"BK-CLEAN"}
{"name":"The Pragmatic Programmer","price":650.00,"sku":"BK-PRAG"}
{"name":"Atomic Habits","price":399.00,"sku":"BK-ATOMIC"}
Shared mapper indents: false
Copy indents: trueWhat this code does
MAPPERis created once.parallelStream()converts the three books on several threads at the same time, all using the same mapper, andtoList()keeps the original order.rebuild()returned a new mapper with pretty printing on; the shared one still has it off. There is no setter that could changeMAPPERwhile other threads use it.
Building a mapper is costly: the first time it meets a class, it studies the class and caches how to read and write it. So build one mapper when the program starts, usually as a static final field or, in Spring Boot, as a bean the framework gives you.
A Jackson 3 mapper is immutable: its settings are fixed when build() runs. To get different settings, rebuild() makes a configured copy and leaves the original unchanged.
new JsonMapper inside a method that runs for every request throws away the cache each time. It works, but it wastes CPU and memory under load.writeValueAsString and pretty printing
Serialization turns a Java object into JSON text; deserialization turns JSON text back into an object. In Jackson 3 one class, JsonMapper, does both, and writeValueAsString(object) writes compact JSON.
A product with five getters becomes JSON. The program writes it compact, then pretty-printed.
Example 2 · WriteProductDemo.java: compact and pretty JSON
Runs in: the json-playground Maven project with Jackson 3.1.5
import java.math.BigDecimal;import tools.jackson.databind.json.JsonMapper;
public class WriteProductDemo {
static final JsonMapper MAPPER = JsonMapper.builder().build();
static class Product { private String sku; private String name; private BigDecimal price; private int stock; private boolean active;
Product(String sku, String name, BigDecimal price, int stock, boolean active) { this.sku = sku; this.name = name; this.price = price; this.stock = stock; this.active = active; }
public String getSku() { return sku; } public String getName() { return name; } public BigDecimal getPrice() { return price; } public int getStock() { return stock; } public boolean isActive() { return active; } // boolean getters may start with "is" }
public static void main(String[] args) { Product redmi = new Product("MOB-RN13", "Redmi Note 13 5G", new BigDecimal("17999.00"), 40, true);
String compact = MAPPER.writeValueAsString(redmi); System.out.println(compact); System.out.println("Length: " + compact.length() + " characters");
String pretty = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(redmi); System.out.println(pretty); }}{"active":true,"name":"Redmi Note 13 5G","price":17999.00,"sku":"MOB-RN13","stock":40}
Length: 86 characters
{
"active" : true,
"name" : "Redmi Note 13 5G",
"price" : 17999.00,
"sku" : "MOB-RN13",
"stock" : 40
}What this code does
- Five getters became five JSON properties.
isActive()became"active", and theBigDecimalprice kept both zeros,17999.00. - The keys are in alphabetical order. The same class with Jackson 2 prints
sku,name,price,stock,active, the order of the fields. - The pretty version is longer and easier to read, with a space on both sides of each colon. Send compact JSON; pretty-print for logs and files people read.
writerWithDefaultPrettyPrinter() gives a writer that adds line breaks and two-space indentation, for people reading logs or files; send compact JSON over the network. Jackson finds each value through a public getter: getName() becomes "name", and for a boolean, isActive() becomes "active".
In Jackson 3 the keys of a class like this come out in alphabetical order; Jackson 2 kept the order the getters were declared in. JSON readers match keys by name, so the order does not change the meaning.
Predict the output
What JSON does Jackson 3 write?
Read the code and pick what it prints.
Round 1 of 3
MAPPER.writeValueAsString(new Product()) prints which text?
readValue from a String, a file and an InputStream
Deserialization turns JSON text into a Java object. readValue(source, Type.class) reads a String, a file or an InputStream and returns a new object of that type.
The same readValue call reads a product from a String, from a file and from an InputStream.
Example 3 · ReadProductDemo.java: three sources, one readValue
Runs in: the json-playground Maven project with Jackson 3.1.5
import java.io.InputStream;import java.io.IOException;import java.math.BigDecimal;import java.nio.file.Files;import java.nio.file.Path;import tools.jackson.databind.json.JsonMapper;
public class ReadProductDemo {
static final JsonMapper MAPPER = JsonMapper.builder().build();
static class Product { private String sku; private String name; private BigDecimal price; private int stock;
public Product() { } // Jackson creates the object with this, then calls the setters
public String getSku() { return sku; } public void setSku(String sku) { this.sku = sku; } public String getName() { return name; } public void setName(String name) { this.name = name; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; }
@Override public String toString() { return sku + " | " + name + " | Rs. " + price + " | stock " + stock; } }
public static void main(String[] args) throws IOException { // 1. From a String, such as a request body String json = """ {"sku": "LAP-IPS3", "name": "Lenovo IdeaPad Slim 3", "price": 42990.00, "stock": 12} """; Product fromString = MAPPER.readValue(json, Product.class); System.out.println("From String: " + fromString);
Path dir = Files.createTempDirectory("shoplite"); Path file = dir.resolve("laptop.json"); MAPPER.writeValue(file, fromString); Product fromFile = MAPPER.readValue(file, Product.class); System.out.println("Saved " + file.getFileName() + " (" + Files.size(file) + " bytes)"); System.out.println("From file: " + fromFile);
// 3. From an InputStream, such as an HTTP response body try (InputStream in = Files.newInputStream(file)) { Product fromStream = MAPPER.readValue(in, Product.class); System.out.println("From stream: " + fromStream); }
Files.delete(file); Files.delete(dir); }}From String: LAP-IPS3 | Lenovo IdeaPad Slim 3 | Rs. 42990.00 | stock 12 Saved laptop.json (77 bytes) From file: LAP-IPS3 | Lenovo IdeaPad Slim 3 | Rs. 42990.00 | stock 12 From stream: LAP-IPS3 | Lenovo IdeaPad Slim 3 | Rs. 42990.00 | stock 12
What this code does
- Jackson called the no-arg constructor, then
setSku,setName,setPriceandsetStockfor the four keys.42990.00was read into aBigDecimalexactly. writeValue(file, ...)createdlaptop.jsonin a temporary folder, and bothreadValue(file, ...)andreadValue(in, ...)read the same object back from it.- The text block holds the JSON with no escaped quotes.
Files.createTempDirectorykeeps the demo from leaving files behind; it deletes them at the end.
The source can be a String (a request body you already have), a Path or File (a JSON file on disk) or an InputStream (bytes arriving from a network connection or a file). writeValue(path, object) does the opposite and writes JSON straight into a file.
Prefer the stream or file versions for large inputs: Jackson reads them piece by piece instead of first building one huge String. You still close the stream yourself, with try-with-resources.
What Jackson needs from a class: getters, setters and a no-arg constructor
Property is one named value of a class that Jackson can read or write. Jackson finds it through a getter such as getName() when writing, and through a setter such as setStock(int) when reading.
A class with only private fields and a class with only a two-argument constructor show what Jackson needs to write and to read.
Example 4 · ClassRulesDemo.java: no getters, no no-arg constructor
Runs in: the json-playground Maven project with Jackson 3.1.5
import tools.jackson.core.JacksonException;import tools.jackson.databind.json.JsonMapper;
public class ClassRulesDemo {
static final JsonMapper MAPPER = JsonMapper.builder().build();
// Mistake 1: private fields and no getters, so Jackson sees no properties static class Category { private String name = "Mobiles"; private int productCount = 3; }
// Mistake 2: no no-arg constructor, so Jackson cannot create the object static class Customer { private String fullName; private String email;
Customer(String fullName, String email) { this.fullName = fullName; this.email = email; }
public String getFullName() { return fullName; } public String getEmail() { return email; } }
public static void main(String[] args) { System.out.println("Category as JSON: " + MAPPER.writeValueAsString(new Category()));
String json = "{\"fullName\": \"Meena Iyer\", \"email\": \"meena.iyer@example.com\"}"; try { MAPPER.readValue(json, Customer.class); } catch (JacksonException e) { System.out.println(e.getClass().getSimpleName() + ":"); System.out.println(e.getMessage()); } }}Category as JSON: {}
InvalidDefinitionException:
Cannot construct instance of `ClassRulesDemo$Customer` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); byte offset: #UNKNOWN]What this code does
Categoryhas values, but Jackson can see none of them, so it wrote{}without any error. This silent loss is the more dangerous of the two mistakes.Customerhas only a two-argument constructor, so Jackson has no way to create it: "no Creators, like default constructor, exist".ClassRulesDemo$Customeris how Java names a nested class.- The fixes: add getters to
Category; add a no-arg constructor and setters toCustomer(or turn it into a record).
To write, Jackson needs a public getter or public field for each value. To read, it needs a way to create the object, usually a no-arg constructor (a constructor with no parameters), and a public setter for each value.
The two mistakes behave very differently. A class with only private fields and no getters is written as {} with no error at all, and the data is silently lost. A class without a no-arg constructor fails loudly when read, with InvalidDefinitionException. Records, covered two lessons later, avoid both problems.
static. A non-static inner class needs an outer object to exist, so Jackson cannot create one on its own.Reading the exception when JSON and the class don't match
Reference chain is the path in a Jackson error that names the field that failed, such as Product["stock"]. The error also gives the line and column where the problem was found.
Three bad inputs show the parts of a Jackson error: a wrong type, broken JSON and an array where an object was expected.
Example 5 · MismatchDemo.java: reading the parts of an error
Runs in: the json-playground Maven project with Jackson 3.1.5
import java.math.BigDecimal;import tools.jackson.core.JacksonException;import tools.jackson.databind.json.JsonMapper;
public class MismatchDemo {
static final JsonMapper MAPPER = JsonMapper.builder().build();
static class Product { private String sku; private BigDecimal price; private int stock;
public Product() { }
public String getSku() { return sku; } public void setSku(String sku) { this.sku = sku; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } }
static void tryRead(String label, String json) { try { MAPPER.readValue(json, Product.class); System.out.println(label + ": OK"); } catch (JacksonException e) { System.out.println(label + ": " + e.getClass().getSimpleName()); System.out.println(" message: " + e.getOriginalMessage()); String field = e.getPathReference(); System.out.println(" field: " + (field.isEmpty() ? "(none)" : field)); System.out.println(" location: line " + e.getLocation().getLineNr() + ", column " + e.getLocation().getColumnNr()); } }
public static void main(String[] args) { tryRead("Wrong type", "{\"sku\": \"BK-CLEAN\", \"price\": 499.00, \"stock\": \"thirty\"}"); tryRead("Broken JSON", "{\"sku\": \"BK-CLEAN\", \"price\": 499.00, \"stock\": 30"); tryRead("Array, not object", "[{\"sku\": \"BK-CLEAN\"}]");
try { MAPPER.readValue("{\"sku\": \"BK-CLEAN\", \"stock\": \"thirty\"}", Product.class); } catch (JacksonException e) { System.out.println("Full message:"); System.out.println(e.getMessage()); } }}Wrong type: InvalidFormatException message: Cannot deserialize value of type `int` from String "thirty": not a valid `int` value field: MismatchDemo$Product["stock"] location: line 1, column 47 Broken JSON: UnexpectedEndOfInputException message: Unexpected end-of-input: expected close marker for Object (start marker at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); byte offset: #UNKNOWN]) field: (none) location: line 1, column 49 Array, not object: MismatchedInputException message: Cannot deserialize value of type `MismatchDemo$Product` from Array value (token `JsonToken.START_ARRAY`) field: (none) location: line 1, column 1 Full message: Cannot deserialize value of type `int` from String "thirty": not a valid `int` value at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); byte offset: #UNKNOWN] (through reference chain: MismatchDemo$Product["stock"])
What this code does
- The wrong type names the field,
Product["stock"], and the bad value,"thirty". Broken JSON has no field, only a position: the text ended at column 49 before the closing}. getOriginalMessage()is the message without the location part, which is handy when you build your own error text.getMessage(), at the end, is the full text you see in a stack trace.
Every Jackson 3 error is a JacksonException, an unchecked exception, with more specific subclasses:
InvalidFormatException: a value of the wrong type, such as"thirty"for anint.MismatchedInputException: the wrong shape, such as an array where an object was expected.StreamReadException: the text is not valid JSON at all.
Read three parts of an error: the message says what went wrong, getPathReference() returns the reference chain and getLocation() returns the line and column. Jackson 3 prints Source: REDACTED instead of the input text, so passwords or personal data in a request never end up in your logs.
Next step
Check your understanding
11 quick questions