使用 jsonpb 解组自定义类型
Unmarshal custom types with jsonpb
将此 json 对象转换为 protobuf 的最佳方法是什么?
JSON:
{
"name": "test",
"_list": {
"some1": { "value": 1 },
"some2": [
{ "value": 2 },
{ "value": 3 },
]
}
}
原型:
message Something {
string name = 1;
message ListType {
repeated string = 1;
}
map<string, ListType> _list = 2;
}
如果消息中没有 _list
,我会使用 jsonpb.Unmarsal,但我想不出一种方法来在 diff 包中生成的类型上定义 Unmarshaler 接口。
我还考虑过将 _list
作为 Any (json.RawMessage) 并在 Unmarshal 之后处理它(但无法使其工作;错误消息:Any JSON doesn't have '@type'
)
由于 _list 不一致(不仅仅是 values/etc 中的 strings/map 的列表)并且你提到你研究过使用 Any 你可以考虑发表你的消息:
message Something {
string name = 1;
google.protobuf.Struct _list = 2;
}
https://github.com/golang/protobuf/blob/master/ptypes/struct/struct.proto
你可以 marshal/unmarshal json to/from 使用 github.com/golang/protobuf/jsonpb 原型消息,它实际上是为与 grpc 网关一起使用而设计的,但你也可以使用它
将此 json 对象转换为 protobuf 的最佳方法是什么?
JSON:
{
"name": "test",
"_list": {
"some1": { "value": 1 },
"some2": [
{ "value": 2 },
{ "value": 3 },
]
}
}
原型:
message Something {
string name = 1;
message ListType {
repeated string = 1;
}
map<string, ListType> _list = 2;
}
如果消息中没有 _list
,我会使用 jsonpb.Unmarsal,但我想不出一种方法来在 diff 包中生成的类型上定义 Unmarshaler 接口。
我还考虑过将 _list
作为 Any (json.RawMessage) 并在 Unmarshal 之后处理它(但无法使其工作;错误消息:Any JSON doesn't have '@type'
)
由于 _list 不一致(不仅仅是 values/etc 中的 strings/map 的列表)并且你提到你研究过使用 Any 你可以考虑发表你的消息:
message Something {
string name = 1;
google.protobuf.Struct _list = 2;
}
https://github.com/golang/protobuf/blob/master/ptypes/struct/struct.proto
你可以 marshal/unmarshal json to/from 使用 github.com/golang/protobuf/jsonpb 原型消息,它实际上是为与 grpc 网关一起使用而设计的,但你也可以使用它