Java print protobuf object of unknown type

Note that I have a byte array-byte [], which is some kind of serialized protobuf object. Is there a way to print it for output, something like

1: 123 2: Jhon 3: Doe 4: 0 

Where 1 is int, 2 and 3 are strings, and 4 is boolen

TextFormat.print requires me to provide a specific Builder for the protobuf object that I do not know.

+5
source share
2 answers

Define the EmptyMessage type as:

 message EmptyMessage { // nothing } 

Now EmptyMessage your message as EmptyMessage , then call toString() on it.

Why does it work? Well, keep in mind that it is backward compatible to add fields to the message type. When you add a field, then send a message, using this field, to an old program that was not built with knowledge of the field, then the field is considered as an "unknown field". Unknown fields are printed as number / value pairs. Now, if you start with EmptyMessage and add fields, you can get any other message. Therefore, all message types are "backward compatible" with EmptyMessage . Therefore, any message can be parsed as an EmptyMessage to process all fields as unknown fields.

+4
source

if we can make the assumption that the fields are all primitive types (i.e. not sub-messages), then you should be able to completely scroll through all the fields -

 for(Entry<FieldDescriptor, Object> entry : msg.getAllFields().entrySet()) { if(entry.getValue() != null) System.out.println(entry.getKey().getName() + ": " + entry.getValue().toString()); else System.out.println(entry.getKey().toString() + ": null"); } 

However, I'm sure protobuf objects implement the toString () method correctly, so I think you should just call

 protoObj.toString() 

to get a string representation of the protobuf object. For more information, check out: https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/GeneratedMessage.ExtendableMessage#getAllFields%28%29

+1
source

Source: https://habr.com/ru/post/1245018/


All Articles