Protobuf - Object with optional arrays

2.5k views Asked by At

I have an object that is something like this:

{
  "colorRestrictions": {
    "availableColors":[ ... ], 
    "excludedColors": [ ... ]
  }
}

How do I translate this into a proto file considering that colorRestriction is an object that can have either of the arrays?

The property oneof doesn't allow for repeated within the declaration.

I guess it's something common but I couldn't find a straight answer, any suggestions? Thanks

1

There are 1 answers

0
Eric Anderson On BEST ANSWER

Fields are all optional in Protobuf 3. So just define ordinary fields.

message ColorRestriction {
  repeated Color available_colors = 1;
  repeated Color excluded_colors = 2;
}

oneof is for mutually-exclusive fields. It doesn't require that a field is present; a oneof can be unset.

Even in Protobuf 2 repeated fields couldn't be marked as required. repeated fields don't have normal field presence because "empty list" is encoded identically to "unset list." When you need presence information in a repeated field (e.g., to include it in a oneof or distinguish "empty list" from "unset list") you can wrap it in a message.

message ColorRestriction {
  ColorList available_colors = 1;
  ColorList excluded_colors = 2;
}

message ColorList {
  repeated Color colors = 1;
}