FasterXML / jackson-dataformats-binary

Uber-project for standard Jackson binary format backends: avro, cbor, ion, protobuf, smile
Apache License 2.0
316 stars 136 forks source link

'Any' type not supported as a type by protobuf #199

Open jfuehner opened 4 years ago

jfuehner commented 4 years ago

Hi! I have the below generic object that I use as a wrapper around other objects when sending a response.

public class Response<T> {
    private T data;

    public Response() {

    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

When I try to generate a byte buffer from the Response object with the below code I receive the error, 'Any' type not supported as a type by protobuf

        ObjectMapper mapper = new ObjectMapper(new ProtobufFactory());
        ProtobufSchemaGenerator generator = new ProtobufSchemaGenerator();
        mapper.acceptJsonFormatVisitor(Response.class, generator);
        ProtobufSchema schema = generator.getGeneratedSchema();

        Response<DataFeedCollection> response = new Response<>();

        byte[] bytes = mapper.writer(schema).writeValueAsBytes(response);
        ByteBuffer buffer = ByteBuffer.wrap(bytes);

        session.sendMessage(new BinaryMessage(buffer));

Are generics not supported? Would there be an alternative to this generics approach?

cowtowncoder commented 4 years ago

Protobuf protocol is strong typed so I do not think this can be made to work. I think usual approaches are to either implement "union" type by having multiple optional fields with different types, or, serializing actual value as Blob of nominal type byte[] (binary field in protobuf).

jfuehner commented 4 years ago

@cowtowncoder could the Any pack/unpack methods be used?

https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Any

cowtowncoder commented 4 years ago

@jfuehner That is functionality provided by some other library. Jackson protobuf implementation does not use that library. I have no idea what that does internally.