doukuang1950 2018-04-22 05:41
浏览 1487

在Go中将带有枚举的Protobuf3转换为JSON

How can I convert grpc/protobuf3 message to JSON where the enum is represented as string?

For example, the protobuf message:

enum Level {
    WARNING = 0;
    FATAL = 1;
    SEVERE = 2;
    ...
}

message Http {
    string message = 1;
    Level level = 2;
}

Is converted by:

j, _ := json.MarshalIndent(protoMessage, "", "\t")

To:

{
    "message": "Hello world!",
    "level": 2,
}

I wish to get:

{
    "message": "Hello world!",
    "level": "SEVERE",
}

Thanks

  • 写回答

2条回答 默认 最新

  • drasv0904 2018-04-22 05:48
    关注

    Level is not a string though, it is an emum. There are really only two choices I see.

    1. Write a custom marshaller that does this for you
    2. Generate code that does this for you.

    For #2, gogoprotobuf has an extension (still marked as experimental) that let's you do exactly this:

    https://godoc.org/github.com/gogo/protobuf/plugin/enumstringer and https://github.com/gogo/protobuf/blob/master/extensions.md

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!