Is it possible to parse protobuf in a generic fashion in Java?
I have looked into GeneratedMessage and could not find a way to parse any PB byte buffer into a GeneratedMessage.
Essentially, I am trying to parse a PB byte buffer into GeneratedMessage and then I would use reflection to detect fields inside it.
First of all, you can't parse PB data without knowing the schema. The schema originally comes from a ".proto" file and is typically embedded in the code generated by
protoc
. However, you can also tellprotoc
to store the schema in a format that's usable by the Java Protobuf library:Then load it in your Java code:
Once you have the schema for a message (
Descriptor.Descriptor
) parsing a message is easy:DynamicMessage
has a reflective API that lets you look through the fields.The messy part is calling out to the
protoc
tool to convert the ".proto" file into a usable format. The C++ Protobuf library has a way to load ".proto" files directly, but unfortunately the Java Protobuf library does not.This is right example:
You can use UnknownFieldSet to parse generic protobuf messages.
Then you can get individual fields using provided methods (e.g. asMap(), hasField(), getField())
E.g. (data taken from this question):
Giving:
I have working solution tested with last protobuf v.3.1.0
This is upgraded solution raised on previous answers. Thanks to both authors.