package com.ankurm.objectmapper; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.TreeSet; import com.fasterxml.jackson.annotation.JsonInclude; /** Why Jackson 3 removed the setters: configuring a Jackson 2 mapper after first use is unreliable. */ public class P02ImmutableMapper { private static List mutators(Class c) { return new TreeSet<>(Arrays.stream(c.getMethods()) .map(Method::getName) .filter(n -> n.startsWith("set") || n.equals("configure") || n.equals("enable") || n.equals("disable") || n.startsWith("register") || n.equals("addMixIn") || n.startsWith("activateDefaultTyping") || n.equals("findAndRegisterModules")) .toList()).stream().toList(); } public static void main(String[] args) throws Exception { System.out.println("== public mutator methods on the mapper class =="); System.out.println("Jackson 2 ObjectMapper : " + mutators(com.fasterxml.jackson.databind.ObjectMapper.class).size() + " distinct names"); System.out.println("Jackson 3 ObjectMapper : " + mutators(tools.jackson.databind.ObjectMapper.class).size() + " distinct names"); System.out.println("Jackson 3 JsonMapper : " + mutators(tools.jackson.databind.json.JsonMapper.class).size() + " distinct names"); System.out.println(" the one Jackson 3 name that matched: " + mutators(tools.jackson.databind.ObjectMapper.class) + " (a getter, not a setter)"); System.out.println(); Article withNull = new Article(1L, "Jackson Deep Dive", List.of("java")); // subtitle == null // ---- Jackson 2: change the inclusion rule AFTER the mapper has already serialised an Article ---- com.fasterxml.jackson.databind.ObjectMapper m2 = new com.fasterxml.jackson.databind.ObjectMapper(); System.out.println("== Jackson 2: reconfigure after first use =="); System.out.println("before : " + m2.writeValueAsString(withNull)); m2.setSerializationInclusion(JsonInclude.Include.NON_NULL); System.out.println("after setSerializationInclusion(NON_NULL) : " + m2.writeValueAsString(withNull)); com.fasterxml.jackson.databind.ObjectMapper fresh2 = new com.fasterxml.jackson.databind.ObjectMapper(); fresh2.setSerializationInclusion(JsonInclude.Include.NON_NULL); System.out.println("fresh mapper, same setting : " + fresh2.writeValueAsString(withNull)); System.out.println(); // ---- Jackson 3: the mapper is final-config; derive a new one with rebuild() ---- tools.jackson.databind.json.JsonMapper m3 = tools.jackson.databind.json.JsonMapper.builder().build(); System.out.println("== Jackson 3: rebuild() derives a new mapper =="); System.out.println("original : " + m3.writeValueAsString(withNull)); tools.jackson.databind.json.JsonMapper nonNull = m3.rebuild() .changeDefaultPropertyInclusion(i -> i.withValueInclusion(JsonInclude.Include.NON_NULL)) .build(); System.out.println("rebuilt NON_NULL : " + nonNull.writeValueAsString(withNull)); System.out.println("original again : " + m3.writeValueAsString(withNull)); System.out.println("same instance? : " + (m3 == nonNull)); } }