怀念夏天 发表于 2023-8-1 15:14:35

Protobuf中如何指定json tag

在 Protocol Buffers (protobuf) 中,可以使用特定的选项来指定生成的 JSON 标签。通过在消息定义中使用 [(json_name)] 选项,可以控制生成的 JSON 字段名称。这样可以确保 Protocol Buffers 和 JSON 之间的互操作性。
下面是一个示例 protobuf 消息定义,其中指定了生成的 JSON 标签:
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_name 和 email_address 字段上使用了 [(json_name)] 选项。这样,当使用 Protocol Buffers 序列化为 JSON 时,生成的 JSON 将使用指定的标签名称。
示例 JSON 输出:
{
"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 标签。
https://img2023.cnblogs.com/blog/1007709/202305/1007709-20230511101217207-642908395.jpg声明:本作品采用署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)进行许可,使用时请注明出处。
Author: mengbin
blog: mengbin
Github: mengbin92
cnblogs: 恋水无意

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Protobuf中如何指定json tag