go - 为 protobuf 消息字段定义自定义 go struct 标签

标签 go protocol-buffers grpc

我是 grpc 的新手,一直在尝试从网络服务器获取 json 响应。然后 stub 可以从 rpc 服务器请求 json

在我的 .proto 文件中,我创建了一个消息类型:

message Post {
    int64 number = 1;
    string now = 2;
    string name = 3;
}

但是我无法编码 number 字段,因为 protoc 会生成带有 number 的结构 pb.go 文件 标签:

{
        "no": "23",
        "now": "12:06:46",
        "name": "bob"
}

我怎样才能强制 Message 使用消息字段的小写名称以外的标记进行“转换”?比如使用json标签no,即使Message中的字段名是number

最佳答案

您可以使用 json_name

在 proto 消息定义上设置 proto3 字段选项
message Post {
    int64 number = 1 [json_name="no"];
    string now = 2;
    string name = 3;
}

link to the docs

关于go - 为 protobuf 消息字段定义自定义 go struct 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51828804/

相关文章:

Java:有人有一个通过网络使用谷歌 Protocol Buffer 的示例项目吗?

java - Protocol Buffer 和枚举组合?

java - 如何在grpc中配置最大同时连接数

c# - 如何在与 C# 相同的 gRPC 中声明小数对象

golang,我可以使用 rsa key 创建 X509KeyPair 吗?

Go:扩展未命名类型,例如 []string

json - 将 slice 结果 JSON 插入 MongoDB

c++ - ProtoBuf 编译链接 GCC

go - 将未编码的 yaml interface{} 转换为实际结构

去隐式转换接口(interface)做内存分配?