【问题标题】:How to define com.google.protobuf.Message as message type in .proto file如何在 .proto 文件中将 com.google.protobuf.Message 定义为消息类型
【发布时间】:2023-03-19 10:57:01
【问题描述】:

如何在 proto 文件中定义通用消息。

例如:

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

我需要以下协议,而不是上面提到的协议。

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

我需要在response 中设置Foo 或Bar 或Baz 值。 有什么方法可以实现吗?

【问题讨论】:

    标签: protocol-buffers proto3


    【解决方案1】:

    我建议oneof 是你最好的选择:

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

    您也可以使用 Any,但在 IMO 中这将是一个错误,并且会让您的事情变得更加困难。

    【讨论】:

    • 但是我会得到这样的结果:“status: true bar { id: 6 }”。我期望的是“状态:真实响应 { id:6 }”。
    • @prasath 是的,因为没有它:你不会知道它代表什么。序列化程序想知道。
    • 像java中的对象我需要在proto文件中定义Message。如果不可能,我会选择“oneof”。
    • @Prasath 最接近 Object 的是 Any。不过,这确实意味着您必须做额外的工作才能获取价值。但是:IMO 这是一个错误。我怀疑,您通常实际上并不是指“任何” - 通常您的意思是“这些预期类型中的未知类型”。这将是:“一个”
    • 我会选择“oneof”
    猜你喜欢
    • 2021-11-20
    • 2019-12-10
    • 1970-01-01
    • 2020-03-15
    • 2021-12-30
    • 1970-01-01
    • 2020-11-23
    • 2018-11-09
    • 2022-12-03
    相关资源
    最近更新 更多