How to convert from Json to Protobuf?

Karan Tibrewal picture Karan Tibrewal · Jul 16, 2016 · Viewed 50.5k times · Source

I'm new to using protobuf, and was wondering if there is a simple way to convert a json stream/string to a protobuf stream/string in Java?

For example,

protoString = convertToProto(jsonString)

I have a json string that I want to parse into a protobuf message. So, I want to first convert the json string to protobuf, and then call Message.parseFrom() on it.

Thanks in advance for the help!

Answer

Adam Cozzette picture Adam Cozzette · Jul 18, 2016

With proto3 you can do this using JsonFormat. It parses directly from the JSON representation, so there is no need for separately calling MyMessage.parseFrom(...). Something like this should work:

JsonFormat.parser().merge(json_string, builder);