java 36 lines · 8 steps

Configuring a reusable Jackson ObjectMapper

One tuned ObjectMapper drives several serialization variants for Order objects.

Explained by highlit
1public class OrderSerializer {
2 
3 private final ObjectMapper mapper;
4 
5 public OrderSerializer() {
6 this.mapper = JsonMapper.builder()
7 .addModule(new JavaTimeModule())
8 .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
9 .serializationInclusion(JsonInclude.Include.NON_NULL)
10 .build();
11 this.mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
12 }
13 
14 public String toJson(Order order) throws JsonProcessingException {
15 return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(order);
16 }
17 
18 public byte[] toBytes(Order order) throws JsonProcessingException {
19 return mapper.writeValueAsBytes(order);
20 }
21 
22 public void writeTo(Path target, Order order) throws IOException {
23 try (OutputStream out = Files.newOutputStream(target)) {
24 mapper.writeValue(out, order);
25 }
26 }
27 
28 public String toJsonView(Order order) throws JsonProcessingException {
29 return mapper.writerWithView(Views.Public.class).writeValueAsString(order);
30 }
31 
32 public String toJsonArray(List<Order> orders) throws JsonProcessingException {
33 ObjectWriter writer = mapper.writerFor(new TypeReference<List<Order>>() {});
34 return writer.writeValueAsString(orders);
35 }
36}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Build and configure a single ObjectMapper once, then reuse it for every serialization call.
  2. 2ObjectMapper's writer methods return specialized writers without mutating the shared mapper.
  3. 3TypeReference preserves generic type information that Java erasure would otherwise lose.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Configuring a reusable Jackson ObjectMapper — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code