Using Jackson Without Annotations To Quickly Add Logging Of Object-Graphs As JSON

Normally, you have to add Annotations to your classes, if you want to serialize them with Jackson.
The following snippet shows, how you can configure Jackson in order to serialize vanilla classes without adding annotations.
This is usefull, if you want to add logging-statements, that print out graphs of objects in JSON-notation for classes, that are not prepared for serialization.


ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String str = mapper.writeValueAsString(new Bar());

I have put together a tiny sample-project, that demonstrates the approach.
URL for cloning with GIT:
https://juplo.de/git/demos/noanno/

It can be executed with mvn spring-boot:run

How To Keep The Time-Zone When Deserializing A ZonedDateTime With Jackson

The Problem: Jackson Loses The Time-Zone During Dezerialization Of A ZonedDateTime

In its default configuration Jackson adjusts the time-zone of a ZonedDateTime to the time-zone of the local context.
As, by default, the time-zone of the local context is not set and has to be configured manually, Jackson adjusts the time-zone to GMT.

This behavior is very unintuitive and not well documented.
It looks like Jackson just loses the time-zone during deserialization and, if you serialize and deserialize a ZonedDateTime, the result will not equal the original instance, because it has a different time-zone.

The Solution: Tell Jackson, Not To Adjust the Time-Zone

Fortunately, there is a quick and simple fix for this odd default-behavior: you just have to tell Jackson, not to adjust the time-zone.
Tis can be done with this line of code:

mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

Funded by the Europian Union

This article was published in the course of a
resarch-project,
that is funded by the European Union and the federal state Northrhine-Wetphalia.


Europäische Union: Investitionen in unsere Zukunft - Europäischer Fonds für regionale Entwicklung
EFRE.NRW 2014-2020: Invesitionen in Wachstum und Beschäftigung