在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

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

I found out that I should use the protobuf/jsonpb package and not the standard json package.

so:

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

Should be:

m := jsonpb.Marshaler{}
result, _ := m.MarshalToString(protoMessage)