Consider that I have byte array - byte[] which represent some kind of serialized protobuf object. Is there any way to print it to output, something like
1: 123
2: Jhon
3: Doe
4: 0
Where 1 is int field, 2 and 3 are strings and 4 is boolen
TextFormat.print requires me to provide concrete Builder of protobuf object, which I do not know.
Define a type EmptyMessage
like:
message EmptyMessage {
// nothing
}
Now parse your message as EmptyMessage
, then call toString()
on it.
Why does this work? Well, consider that it is backwards-compatible to add fields to a message type. When you add a field, then send a message using that field to an old program that wasn't build with knowledge of the field, then the field is treated as as "unknown field". Unknown fields are printed as number / value pairs. Now, if you start with EmptyMessage
and add fields, you can obviously get any other message. Therefore, all message types are "backwards-compatible" with EmptyMessage
. Therefore, any message can be parsed as EmptyMessage
to treat all the fields as unknown fields.
if we can make the assumption that the fields are all primitive types (i.e. not sub-messages) then you should be able to loop through all the fields very simply -
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 am pretty sure that protobuf objects properly implement the toString() method, so I think you should be able to simply call
protoObj.toString()
to get a string representation of the protobuf object. For more info, take a look at: https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/GeneratedMessage.ExtendableMessage#getAllFields%28%29
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With