简体   繁体   中英

ProtoBuf - Can a field support two possible datatypes?

is it possible for one field in protobuf to support/accept a string or an array of string. This is my message:

message MessageA {
  string fieldId =1;
  string method = 2;
  google.protobuf.Any value =3;
}

The reason for it being dynamic is because an array of string or a simple string can be the input. There are separate methods on what will happen if the payload is string[] or string.

Right now, I'm using any but I'm not sure what to do in the any file. I've read that oneof does not support array data types thats why I'm trying to make it work with any .

Here is the error message when I try to put a repeated inside a oneof : 在此处输入图像描述

No, basically. The main way of doing this would be to have two inner-types - one with a single-valued member, one with a repeated member, and have a oneof that covers the two inner-types. Or perhaps simpler: just have a repeated and separately have an enum, boolean, or other indicator to choose between the two possible meanings (so you can tell between "an array, that happened to have exactly one item" vs "the single value").

For anyone that might have the same problem as me, you can use google.protobuf.Value . There would be an additional object but it can be transformed using UsePipe so it shouldn't be a problem.

Here is the documentation: https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM