【问题标题】:Unmarshal custom types with jsonpb使用 jsonpb 解组自定义类型
【发布时间】:2018-04-13 23:09:25
【问题描述】:

将此 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'

【问题讨论】:

    标签: go protocol-buffers grpc


    【解决方案1】:

    由于 _list 不一致(不仅仅是字符串列表/值映射/等),并且您提到您考虑使用 Any 您可以考虑发送消息:

    message Something { string name = 1; google.protobuf.Struct _list = 2; }

    https://github.com/golang/protobuf/blob/master/ptypes/struct/struct.proto

    您可以使用 github.com/golang/protobuf/jsonpb 编组/解组 json 到/来自原始消息,这实际上是为与 grpc 网关一起使用而设计的,但您也可以使用它

    【讨论】:

    • 任何关于如何使用jsobpb 将 json 字符串转换为 proto 结构类型的代码示例都会有所帮助。
    猜你喜欢
    • 2022-06-28
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    相关资源
    最近更新 更多