查看奇怪的协议缓冲区消息(解码和编码)

Looking into weird protocol-buffer message (decoding and encoding)

我想弄清楚,有没有一种方法可以创建 .proto 定义,它可以创建和解码如下所示的消息:

parent_field {
   carrier_field { (field id: 1)
       subfield_1: 10 (field id: 1)
       subfield_2: 20 (field id: 2)
   }
   carrier_field: "string" (field id: 1)
}

这意味着在相同的字段标识符下我可以获得子消息或字符串。

我试过类似的方法:

message MessageWrapper {
   message ParentField {
      message SubMessage {
          ....
      }
      repeated SubMessage carrier_field = 1
   }
   ParentField parent_field = 1
}

但是当我尝试解码消息时,我得到:

# protoc --experimental_allow_proto3_optional  --decode MessageWrapper proto_definitions/test.proto < test.buff 
Failed to parse input.

.proto 定义应该如何解码和编码上面显示的消息?

这样做的唯一方法是让 carrier_field 成为一个 bytes 字段,然后您可以将其单独解码为字符串或 protobuf 消息。坦率地说,我不建议这样做:最好使用具有不同字段编号的 oneof