Sending protobuf as JSON in spring-boot

Class UnknownFieldSet (reached via generated method Hash.getUnknownFields()) contains getter getDefaultInstanceForType() which returns singleton instance of UnknownFieldSet. This singleton instance references itself in getDefaultInstanceForType() and Jackson-databind can't handle this automatically (see edit2 below).

You might want to use JsonFormat from com.google.protobuf:protobuf-java-util which uses canonical encoding instead of Jackson.

Good luck!

EDIT> For Spring there is ProtobufJsonFormatHttpMessageConverter

EDIT2> Of course you could handle this situation using Mix-in Annotations, but IMHO JsonFormat is definitely the way to go...


If you're using Spring WebFlux and trying to produces application/json here is what you can do to make it works for all mappings returning protobuf Message type:

@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

@Override
public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
    configurer.defaultCodecs().jackson2JsonEncoder(
        new Jackson2JsonEncoder(Jackson2ObjectMapperBuilder.json().serializerByType(
                Message.class, new JsonSerializer<Message>() {
                    @Override
                    public void serialize(Message value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                        String str = JsonFormat.printer().omittingInsignificantWhitespace().print(value);
                        gen.writeRawValue(str);
                    }
                }
        ).build())
    );
}

To convert the protobuf object to JSON, you should be using the following class from the package com.google.protobuf.util.JsonFormat as:

JsonFormat.printer().print()