2

How to define generic message in proto file.

Eg :

message GenericResponse
{
    bool status = 1;
    Foo foo= 2;
    Bar bar = 3;
    Baz baz = 4;
}

Instead of above mentioned protocol I need following protocol.

message GenericResponse
{
    bool status = 1;
    google.protobuf.Message response = 2;
}

I need to set Foo or Bar or Baz values in response. Is there any way to achieve this ?

Prasath
  • 1,233
  • 2
  • 16
  • 38

1 Answers1

2

I would suggest that oneof is your best bet:

message GenericResponse
{
    bool status = 1;
    oneof response {
        Foo foo= 2;
        Bar bar = 3;
        Baz baz = 4;
    }
}

You could also use Any, but IMO that would be a mistake and would make things harder for you.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • But I will get the result like this : "status: true bar { id: 6 }". What I Expect is "status: true response { id: 6 }" . – Prasath Dec 25 '17 at 16:53
  • @prasath yes, because without that : you won't know which it represents. The serializer wants to know. – Marc Gravell Dec 25 '17 at 19:46
  • Like Object in java I need to define Message in proto file. If not possible I will go with "oneof". – Prasath Dec 26 '17 at 06:45
  • @Prasath the closest thing to Object is Any. It does mean hat you'll have to do extra work to fetch the value, though. But: IMO this is a mistake. You don't usually actually mean "any" - usually you mean "an unknown one of these expected types", I suspect. Which would be: "oneof" – Marc Gravell Dec 26 '17 at 10:35
  • I ll go with "oneof" – Prasath Dec 26 '17 at 10:41
  • Hi Marc...Can you please educate me how to exercise a simple helloworld program using protobuf?Its confusing.Can you plz point to step by step tutorial? – sskumar86 Dec 26 '17 at 10:42
  • @sskumar86 refer to the documentation of either protobuf or your specific library. If you have a specific question, you'd need to explain what is still unclear after reading the documentation – Marc Gravell Dec 26 '17 at 11:09