前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Protobuf中如何指定json tag

Protobuf中如何指定json tag

作者头像
孟斯特
发布2023-10-16 19:43:53
4610
发布2023-10-16 19:43:53
举报
文章被收录于专栏:code人生code人生

在 Protocol Buffers (protobuf) 中,可以使用特定的选项来指定生成的 JSON 标签。通过在消息定义中使用 [(json_name)] 选项,可以控制生成的 JSON 字段名称。这样可以确保 Protocol Buffers 和 JSON 之间的互操作性。

下面是一个示例 protobuf 消息定义,其中指定了生成的 JSON 标签:

代码语言:javascript
复制
syntax = "proto3";

message Person {
  string name = 1;
  int32 age = 2;
  string email = 3;

  // 指定生成的 JSON 标签为 "full_name"
  string full_name = 4 [(json_name) = "full_name"];

  // 指定生成的 JSON 标签为 "email_address"
  string email_address = 5 [(json_name) = "email_address"];
}

在上面的例子中,我们定义了一个 Person 消息,并在 full_nameemail_address 字段上使用了 [(json_name)] 选项。这样,当使用 Protocol Buffers 序列化为 JSON 时,生成的 JSON 将使用指定的标签名称。

示例 JSON 输出:

代码语言:javascript
复制
{
  "name": "John",
  "age": 30,
  "email": "john@example.com",
  "full_name": "John Doe",
  "email_address": "john@example.com"
}

请注意,在使用 [(json_name)] 选项时,需要确保标签名称在 JSON 对象中是唯一的,以避免冲突。此外,[(json_name)] 选项只能在 protobuf v3 中使用。在旧版本的 protobuf 中,可以使用 [(name)] 选项来实现类似的功能,但不支持生成的 JSON 标签。

声明:本作品采用署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)[1]进行许可,使用时请注明出处。 Author: mengbin[2] blog: mengbin[3] Github: mengbin92[4] cnblogs: 恋水无意[5]

References

[1] 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0): https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh [2] mengbin: mengbin1992@outlook.com [3] mengbin: https://mengbin.top [4] mengbin92: https://mengbin92.github.io/ [5] 恋水无意: https://www.cnblogs.com/lianshuiwuyi/

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2023-08-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 孟斯特 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • References
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档