Parsing Protocol Buffers, written in Java and read

2019-07-16 13:37发布

问题:

I am dealing with a situation where the protocol buffers have been written to in Java, but I have to read them using Python.

I have the .proto file with me, I have compiled it using protoc, and generated the python class file.

The proto file has multiple messages, for example:

message ABC {
    optional int64 id = 1 [default = -1];
    optional int64 hello6 = 2;
    optional bool hello5 = 3 [default = true];
    optional int32 hello4 = 4;
    optional int64 hello3 = 5;
    optional int64 hello2 = 6;
    optional int64 duration = 7;
}
message DEF {
    optional int64 hello = 1;
    repeated ABC abc = 5;
    repeated String xyz = 6;
  }

While parsing in python using .ParseFromString.

I am getting the error:

google.protobuf.message.DecodeError: Tag had invalid wire type.

I think the issue is because of absence of explicit delimiters, any idea how to solve it?

回答1:

I had similar issue for me this worked:

In Java you do:

yourGeneratedClass.toByteArray()

In Python you do(parsed message in result):

result = your_pb2.yourGeneratedClass()
result.ParseFromString(body)