将此 json 对象转换为 protobuf 的最佳方法是什么?
JSON:
{
"name": "test",
"_list": {
"some1": { "value": 1 },
"some2": [
{ "value": 2 },
{ "value": 3 },
]
}
}
原型(prototype):
message Something {
string name = 1;
message ListType {
repeated string = 1;
}
map<string, ListType> _list = 2;
}
如果消息中没有 _list
,我会使用 jsonpb.Unmarsal,但我想不出一种方法来在 diff 包中生成的类型上定义 Unmarshaler 接口(interface)。
我还考虑过将 _list
作为 Any (json.RawMessage) 并在 Unmarshal 之后处理它(但无法使其工作;错误消息:Any JSON does'没有'@type'
)
最佳答案
由于 _list 不一致(不仅仅是字符串列表/值映射等),您提到您研究过使用 Any 您可以考虑发出消息:
消息某事{
字符串名称 = 1;
google.protobuf.Struct _list = 2;
}
https://github.com/golang/protobuf/blob/master/ptypes/struct/struct.proto
有了它,您可以使用 github.com/golang/protobuf/jsonpb 将 json 编码到原型(prototype)消息或从原型(prototype)消息中解码它实际上是为与 grpc 网关一起使用而设计的,但你也可以使用它
关于go - 使用 jsonpb 解码自定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49826236/