Open pdepietri opened 1 week ago
Hi @pdepietri - we support custom marshallers via jackson-databind integration such as this
Will that work for you? Also see https://github.com/curioswitch/protobuf-jackson/issues/12#issuecomment-1543228596 for some background on the goals of this library, notably we don't intend for the core to have additional features compared to upstream (we would be happy to implement them after upstream does). For custom marshalling, we found it to work well as an implementation of jackson-databind's abstraction though.
@pdepietri we were able to do this after #12 got merged. We use it like this:
SimpleModule customSerializers = new SimpleModule();
JsonSerializer<YourProto> serializer = new StdSerializer<>(YourProto.class) {
@Override
public void serialize(YourProto value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(serializeToString(value));
}
};
JsonDeserializer<YourProto> deserializer = new StdDeserializer<>(YourProto.class) {
@Override
public YourProto deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String value = p.getValueAsString();
return deserializeFromString(value);
}
};
customSerializers.addDeserializer(YourProto.class, deserializer).addSerializer(serializer);
private static MessageMarshaller marshaller = MessageMarshaller.builder()
.omittingInsignificantWhitespace(true)
.preservingProtoFieldNames(true)
.build();
public static ObjectMapper mapper = new ObjectMapper().registerModule(MessageMarshallerModule.of(marshaller))
.registerModule(customSerializers);
Now you can use the Jackson mapper
to (de-)serialize proto to json, and have a custom serialization format for YourProto
.
Thanks you for a great project!
I am trying to use the extended Google types, such as google.type.Date in my project and would like the ability to add custom WellKnownTypeMarshaller in order to serialize dates using ISO 8601 date format instead of the individual fields.
Sample proto:
Produces the following JSON output
The desired output would be
Adding support for custom marshallers would require making WrapperMarshaller and WellKnownTypeMarshaller and their constructors public and adding a method to MessageMarshaller builder in order to add custom type marshallers.
Sample custom marshaller for google.type.Date:
MessageMarshaller builder would look something like this: