package com.ankurm.jackson3.beyond; import com.fasterxml.jackson.annotation.JsonInclude; import tools.jackson.databind.DeserializationFeature; import tools.jackson.databind.PropertyNamingStrategies; import tools.jackson.databind.json.JsonMapper; /** * BEYOND THE POSTS — how to vary configuration once the mapper is immutable. * * The Jackson 2 habit of grabbing the shared mapper and calling configure() on it is * impossible in Jackson 3 — there are no mutators. The replacements are rebuild(), * which forks a builder from an existing mapper, and reader()/writer() views for * per-call tweaks. Neither disturbs the shared instance. */ public class Y04ImmutableMapperAndReaders { public record UserProfile(String firstName, String lastName, String middleName) { } public static void main(String[] args) { JsonMapper shared = JsonMapper.builder().build(); UserProfile user = new UserProfile("Ada", "Lovelace", null); System.out.println("shared : " + shared.writeValueAsString(user)); // 1. rebuild(): fork the shared mapper's configuration and change one thing. JsonMapper snakeCase = shared.rebuild() .propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE) .changeDefaultPropertyInclusion(i -> i.withValueInclusion(JsonInclude.Include.NON_NULL)) .build(); System.out.println("rebuilt snake_case : " + snakeCase.writeValueAsString(user)); // 2. The shared mapper is untouched by the fork. System.out.println("shared unchanged : " + shared.writeValueAsString(user)); // 3. writer()/reader() views for a single call, no new mapper needed. System.out.println("writer view pretty : " + shared.writer().withDefaultPrettyPrinter().writeValueAsString(user) .replace("\n", " ").replaceAll("\\s+", " ")); System.out.println("reader view strict : " + readStrict(shared)); } private static String readStrict(JsonMapper shared) { String json = "{\"firstName\":\"Ada\",\"lastName\":\"Lovelace\",\"unexpected\":1}"; try { shared.reader() .with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .forType(UserProfile.class) // ObjectReader has no readValue(String, Class) .readValue(json); return "accepted"; } catch (Exception e) { return "rejected (" + e.getClass().getSimpleName() + ") without touching the shared mapper"; } } }