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);
String str = mapper.writeValueAsString(new Bar());

I have put together a tiny sample-project, that demonstrates the approach. URL for cloning with GIT:

It can be executed with mvn spring-boot:run

Leave a Reply

Your email address will not be published. Required fields are marked *