Java: JSON -> Protobuf & back conversion

Denis Kulagin picture Denis Kulagin · Feb 16, 2015 · Viewed 99.9k times · Source

I have an existing system, which is using protobuf-based communication protocol between GUI and server. Now I would like to add some persistence, but at the moment protobuf messages are straight converted to a third-party custom objects.

Is there a way to convert proto messages to json, which could be then persisted to database.

N.B.: I don't much like an idea of writing binary protobuf to database, because it can one day become not backward-compatible with newer versions and break the system that way.

Answer

Ophir Radnitz picture Ophir Radnitz · Mar 5, 2017

As mentioned in an answer to a similar question, since v3.1.0 this is a supported feature of ProtocolBuffers. For Java, include the extension module com.google.protobuf:protobuf-java-util and use JsonFormat like so:

JsonFormat.parser().ignoringUnknownFields().merge(json, yourObjectBuilder);
YourObject value = yourObjectBuilder.build();