Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google ProtocolBuffer deserialization type

I would like know how can I retrieve the type of a protobuf loaded from the bytes.

Ex:

Worklist work = Worklist.newBuilder().build();
byte[] msg = work.toByteArray();

Basically I need to find a way to retrieve msg type and should be printing Worklist.

Thanks.

like image 505
user1757189 Avatar asked Dec 06 '25 09:12

user1757189


1 Answers

Protobuf messages are not inherently self describing. You need to know the message type before you parse the bytes. In your case, the code that is about the parse the byte array msg, must know that those bytes represent a Worklist, then invoke the parse implementation in the Worklist class.

However as described in Techniques you can design classes which provide their meta-data as part of the payload.

[update]

Another approach - particularly when you are using protobuf to create messages for sending/receiving is to define a top level message class. All sent/received messages are of this type. Then for the various type of content that might be contained in this message (for example WorkItem), use protobuf extensions. I think the documentation on extensions is a little better than on self describing messages.

Both sides need to know the available extensions, but once you have parsed the message you can query the message object dynamically to see which extensions (like WorkItem) have been filled in.

like image 100
Guido Simone Avatar answered Dec 07 '25 21:12

Guido Simone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!