Search code examples
javajsonserializationjacksonjavaparser

Serialize Javaparser objects with Jackson Json


I'm trying to serialize Javaparser objects with Jackson JSON, but it's pretty complicated as it is a third party library (I can't change/annotate the code) and there are circular dependencies within it.

My project is structured as such :

An object Analysis contains some lists of WrappedNode that may reference each other. Each WrappedNode contains a JavaParser CallableDeclaration.

When I try to map my Analysis, I've got an error :

JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.github.javaparser.metamodel.PropertyMetaModel["containingNodeMetaModel"]->com.github.javaparser.metamodel.SimpleNameMetaModel["declaredPropertyMetaModels"]->java.util.ArrayList[0]->com.github.javaparser.metamodel.PropertyMetaModel["containingNodeMetaModel"]...

So, to get rid of the infinite recursion, I know I have to use @JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id"), which I did on my WrappedNode class, but I think I should also annotate JavaParser classes using Mix-in annotations.

The problem is that there is a lot of fields and a lot of classes, and I don't know which ones to annotate.

Thank's for your help !


Solution

  • You can just use the JsonPrinter class provided by JavaParser. It is a very recent addition (from version 3.2.8 I think) and it could not be perfect but you can use it super, super easily