Jackson API beyond ObjectMapper

aka ObjectReader/ObjectWriter, JsonMapper.builder FTW

“Classic” Jackson API w/ ObjectMapper

ObjectMapper mapper = new ObjectMapper();// Changes to defaults: no fail on reading unknown properties;
// do use default indenting ("pretty-printing") mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// and then read, convert, modify, write:
MyValue v = mapper.readValue(new File("value.json"), MyValue.class);
Map<String, Object> asMap = mapper.convertValue(v, Map.class);
asMap.put("extra", 123);
String jsonModified = mapper.writeValueAsString(asMap);

ObjectReader and ObjectWriter: light-weight and reconfigurable

MyValue v = mapper.readerFor(MyValue.class)
.without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.readValue(new File("value.json"));
Map<String, Object> asMap = mapper.convertValue(v, Map.class);
asMap.put("extra", 123);
String jsonModified = mapper.writer()
.with(SerializationFeature.INDENT_OUTPUT)
.writeValueAsString(asMap);
ObjectReader defaultReader = mapper.reader(); // maybe with configs
ObjectReader valueReader = defaultReader.forType(Value.class);
ObjectWriter defaultWriter = mapper.writer();
ObjectReader indentingWriter = defaultWriter.withDefaultPrettyPrinter();

Safe(r) construction with Builders (2.10+)

ObjectMapper mapper = JsonMapper.builder() // more on this later
.enable(MapperFeature.USE_STD_BEAN_NAMING)
// can also define baseline settings for things we can reconfig:
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
// but mix-ins must be set before use:
.addMixIn(MixIn.class, MyValue.class)
.build();
JsonFactory jsonF = JsonFactory.builder()
// configure
.build();
ObjectMapper mapper = JsonMapper.builder(jsonF)
.enable(...)
.build();

Format-specific mapper subtypes (XmlMapper et al)

ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory());
MyValue v = yamlMapper.readValue(new File("config.yaml"),
MyValue.class);
ObjectMapper xmlMapper = XmlMapper.builder()
.defaultUseWrapper(false) // use "unwrapped" Lists in XML
.disable(ToXmlGenerator.WRITE_XML_DECLARATION)
.build();
// note: we could have held on to XmlMapper, but actual use
// is via readValue(), writeValue() methods
ObjectMapper jsonMapper = JsonMapper.builder()
// non-standard setting for unquoted NaN values:
.disable(JsonWroteFeatire.WRITE_NAN_AS_STRINGS)
.build();

That’s All, Folks!

Open Source developer, most known for Jackson data processor (nee “JSON library”), author of many, many other OSS libraries for Java, from ClassMate to Woodstox