Convert a protobuf to JSON using Jackson?

The current way (Oct-2018) to serialize a protobuf is to use com.google.protobuf.util.JsonFormat in the following manner:

JsonFormat.printer().print(myMessageOrBuilder)

I used the @JsonSerialize(using = MyMessageSerializer.class) annotation right before my protobuf object and added this class:

public static class MyMessageSerializer extends JsonSerializer<Message> {
    @Override
    public void serialize(Message message, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeRawValue(JsonFormat.printer().print(message));
    }
}

This allowed new ObjectMapper().writeValueAsString(wrapperObject) to properly convert my protobuf to JSON.


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.


The include has changed from com.googlecode.protobuf.format.JsonFormat to com.google.protobuf.util.JsonFormat

So, if your protobuf dependency is missing the format package, try looking for JsonFormat in util.

With this include, you should be able to use

new JsonFormat().printToString(myObject)

as @amad-person suggested.