Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: JSON -> Protobuf & back conversion

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.

like image 642
Denis Kulagin Avatar asked Feb 16 '15 15:02

Denis Kulagin


People also ask

Can you convert Protobuf to JSON?

A Printer converts protobuf message to JSON format. A TypeRegistry is used to resolve Any messages in the JSON conversion.

Does Protobuf support JSON?

JSON is limited to certain python objects, and it cannot serialize every python object. Protobuf supports a wider range of data types when compared to JSON. For example, enumerations and methods are supported by Protobuf and not supported by JSON. JSON supports only a subset of python data types.

Is Protobuf better than JSON?

JSON is usually easier to debug (the serialized format is human-readable) and easier to work with (no need to define message types, compile them, install additional libraries, etc.). Protobuf, on the other hand, usually compresses data better and has built-in protocol documentation via the schema.

Is Protobuf lighter than JSON?

Protobuf messages were 9% smaller than JSON messages and they took only 4% less time to be available to the JavaScript code.


1 Answers

We are currently using protobuf-java-format to convert our Protobuf messages (anything subclass of Message) into a JSON format to send over our web API.

Simply do:

  JsonFormat.printToString(protoMessage) 
like image 81
jas_raj Avatar answered Sep 18 '22 22:09

jas_raj