douqie1852 2018-04-13 23:09
浏览 92
已采纳

使用jsonpb解组自定义类型

What's the best way to convert this json object to protobuf?

JSON:

{
  "name": "test",
  "_list": {
    "some1": { "value": 1 },
    "some2": [
      { "value": 2 },
      { "value": 3 },
    ]
  }
}

Proto:

message Something {
     string name = 1;
     message ListType {
       repeated string = 1;
     }
     map<string, ListType> _list = 2;
   }

Without having the _list in the message I would use jsonpb.Unmarsal, but I can't think of a way to define the Unmarshaler interface on a type that is generated in a diff package.

I also thought of having _list as a Any (json.RawMessage) and handle it after the Unmarshal (but can't make this to work; err message: Any JSON doesn't have '@type')

  • 写回答

1条回答 默认 最新

  • dtrpv60860 2018-04-22 03:11
    关注

    With _list being inconsistent (not just a list of strings/map of values/etc) and you mentioning you looked into using Any you could consider making your message:

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

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

    With that you can marshal/unmarshal json to/from proto messages using github.com/golang/protobuf/jsonpb which is actually designed for use with the grpc gateway but you can use it too

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器