JSON转protobuf结构时如何编写支持所有值类型的通用schema
JSON转Protobuf兼容全类型Schema方案
google.protobuf.Value不支持JSON对象、数组的问题属于工具调用适配错误,该类型本身是Protobuf官方专门为兼容任意JSON结构设计的原生类型,支持所有JSON基础数据类型。以下是两种可用的实现方案:
方案1:基于官方标准类型的最简实现(推荐)
直接引入Protobuf官方提供的google/protobuf/struct.proto依赖,不需要额外编写自定义类型,可直接用官方配套的转换工具完成JSON与Protobuf的双向转换。
完整Schema定义
syntax = "proto3"; // 引入官方JSON兼容类型依赖 import "google/protobuf/struct.proto"; // 根结构对应JSON顶层对象 message RootMessage { // 对应JSON中的data数组 repeated DataEntry data = 1; } // 对应data数组中的每个单键值对对象 message DataEntry { // 键为JSON字段名,值为任意JSON类型数据 map<string, google.protobuf.Value> field = 1; }
类型映射规则
- JSON布尔值 →
google.protobuf.Value.bool_value - JSON字符串 →
google.protobuf.Value.string_value - JSON数字 →
google.protobuf.Value.number_value - JSON对象 →
google.protobuf.Value.struct_value - JSON数组 →
google.protobuf.Value.list_value - JSON null →
google.protobuf.Value.null_value
方案2:自定义多类型实现(无外部依赖)
如果不想引入官方struct.proto依赖,可以通过oneof自定义多类型容器实现同等效果,需要自行编写JSON到Protobuf的转换逻辑。
完整Schema定义
syntax = "proto3"; message RootMessage { repeated DataEntry data = 1; } message DataEntry { map<string, CustomValue> field = 1; } // 自定义多类型值容器 message CustomValue { oneof value_type { bool bool_val = 1; string string_val = 2; int32 int_val = 3; int64 long_val = 4; float float_val = 5; double double_val = 6; CustomStruct struct_val = 7; CustomArray array_val = 8; } } // 自定义JSON对象类型 message CustomStruct { map<string, CustomValue> fields = 1; } // 自定义JSON数组类型 message CustomArray { repeated CustomValue items = 1; }
内容的提问来源于stack exchange,提问作者Alex Sparrow
相关产品推荐
相关产品推荐

