Search code examples
protocol-buffers

Parse nested (opaque, any-typed) Protobuf message


I have a message envelope:

import "google/protobuf/any.proto";

message Envelope {
    string type = 1;
    int32 version = 2;
    string message_id = 5;
    string timestamp = 6;
    google.protobuf.Any message = 7;
}

Now, I happen to know that the message is another Protobuf value with the following type: And a message defined as follows:

message Message {
    int32 value = 1;
    string name = 2;
}

Is it possible for me to do a one-shot parsing of this combined message? I am thinking that the problem with substituting Any with Message is the field numbering.


Solution

  • Any is just:

    message Any {
      string type_url = 1;
      bytes value = 2;
    }
    

    where the value is just the regular payload content. If you know that the type is your Message, then you can use instead

    message Envelope {
        string type = 1;
        int32 version = 2;
        string message_id = 5;
        string timestamp = 6;
        FakeAny message = 7;
    }
    message FakeAny {
      // don't even need to capture the type_url
      Message value = 2;
    }
    message Message {
        int32 value = 1;
        string name = 2;
    }
    

    and it should deserialize directly.