I get the following error while converting a protobuf to JSON using Jackson's ObjectMapper:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Direct self-reference leading to cycle (through reference chain:
MyObjectPb$MyObject["unknownFields"]->
com.google.protobuf.UnknownFieldSet["defaultInstanceForType"])
MyObjectPb has the following field:
protected com.google.protobuf.UnknownFieldSet unknownFields
As I am working on an existing codebase, I have the following constraints:
How do I tell Jackson to ignore (de)serializing the UnknownFieldSet object inside MyObjectPb?
I have tried the following, but these approaches do not seem to solve the problem:
a) Configuring the ObjectMapper:
myObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
myObjectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
b) Using a Jackson Mixin:
@JsonIgnoreType
private abstract class UnknownFieldSetIgnoreMixIn {}
myObjectMapper.addMixIn(UnknownFieldSet.class, UnknownFieldSetIgnoreMixIn.class)
I used the JsonFormat class (com.googlecode.protobuf.format.JsonFormat) to convert the protobuf:
new JsonFormat().printToString(myObject)
This did the job perfectly for me.