javaprotocol-buffersgrpcproto3

How to duplicate fields names with proto3 oneof feature?


Proto3 supports the oneof features, where you can have a message with many fields and where at most one field will be set at the same time.

Since one field will be set at a time, it would be reasonable to have duplicate field names in the proto schema. The problem is the proto generater sees this as a redefinition.

I'd like to do this because in my situation, this makes json serialization with JsonFormat simple.

For example, I may like to have

message MyResponse {
    int32 a = 1;
    string b = 2;
    oneof Properties {
        PropertiesType1 properties = 3;
        PropertiesType2 properties = 4;
        PropertiesType3 properties = 5;
        PropertiesType4 properties = 6;
    }
}

Is there a way around this, or will have to make the effort of redefining the proto? A possible work around may be for example to use map<string, Properties> properties = 9;


Solution

  • I have solved similar use case for JSON serialization using this way.

    message MyResponse {
        int32 a = 1;
        string b = 2;
        oneof Properties {
            PropertiesType1 properties1 = 3 [json_name = "properties"];
            PropertiesType2 properties2 = 4 [json_name = "properties"];
            PropertiesType3 properties3 = 5 [json_name = "properties"];
            PropertiesType4 properties4 = 6 [json_name = "properties"];
        }
    }
    

    This would work if you use protoc compilers but it wont work for advanced tools like buf lint/build. Hope this helps.

    But as @marc gravell said this is not recommended way.