Search code examples
javajsonjacksonprotocol-buffers

Convert a protobuf to JSON using Jackson?


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:

  1. I can't modify the source code for MyObjectPb, so I can't use Jackson's ignore annotations in MyObjectPb.
  2. Neither can I use Gson's libraries to convert the object, as the codebase already uses Jackson for serialization. Adding a new dependency is not recommended.

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)

Solution

  • 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.