在 gRPC proto 中将字符串字段声明为 JSON 是一个好方法吗?
由于在 protobuf 中在某些情况下定义灵活的结构很麻烦。
例如:
message Foo {
int a = 1;
repeated int a_other = 2;
}
事实上,我不希望服务的客户端同时传递a
和a_other
。 然而在protobuf中,我们不能将这两个字段放在oneof中,因为a_other是一个列表字段。 因此,通过上面声明的消息,当我们只传递 a_other
字段时,客户端无法判断 a
字段实际上是 0 还是不是服务器传递的。
所以我想知道是否为 Foo
定义一个字符串字段,例如:
message Foo {
string data = 1;
}
并且服务器端和客户端都同意将 data
字段视为 JSON。因此,服务器转储原始数据,客户端加载它,从此他们幸福地生活在一起。
但我的问题是,这样做是常见做法吗?它的缺点是什么? (当然,这样可以放弃类型检查)或者有更好的方法吗?
Since it is quiet trouble some in protobuf to define a flexible structure in some scenario.
for example:
message Foo {
int a = 1;
repeated int a_other = 2;
}
In fact, I don't want the service's client to pass the a
and the a_other
at the same time.
However in protobuf, we can't put these two fields in oneof
because the a_other
is a list field.
So with the above message declared, when we only pass the a_other
field, the client side cannot tell if the a
field is actually 0 or not passed by the server.
So I wonder if define a string field for Foo
like:
message Foo {
string data = 1;
}
and both the server side and the client side is agreed to treat the data
field as a JSON. So the server dumps the primitive data and the client loads it, and they live happily ever after.
But my question is, is it a common practice to do that? And what is the disadvantage of it? (this way drop the type check of course) Or is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
oneof
中的重复字段通常通过包装消息来解决。就您而言:看来您可以轻松地停在那里。
但是,如果您确实发现自己处于“我在这里想要任意 JSON”的情况,那么您可能需要考虑
struct.proto
的Value
而不是普通字符串。Value
可以保存任意 JSON 值。如果您想保存任意 JSON 对象(又名映射),请使用Struct
代替。struct.proto
中的类型是 protobuf 已知的类型,当将 protobuf 消息转换为 JSON 时,它们以原生 JSON 形式表示。但是,在“删除架构并交换为 JSON”之前,您应该参考处理动态内容的不同方法。
Repeated fields in
oneof
are generally solved by a wrapper message. In your case:It seems you can easily stop there.
However, if you do ever find yourself in the "I want arbitrary JSON here" situation, then you would probably want to consider
struct.proto
'sValue
instead of a plain string.Value
can hold an arbitrary JSON value. If you want to hold an arbitrary JSON object (a.k.a., a map) then useStruct
instead. Types instruct.proto
are well-known types known to protobuf and when converting a protobuf message to JSON, they are represented in native JSON form.However, before "dropping the schema and swapping to JSON," you should consult the different ways of handling dynamic content.