Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Protobuf3 with enum to JSON in Go

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

like image 496
michaelbn Avatar asked Apr 22 '18 05:04

michaelbn


Video Answer


3 Answers

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)

Update

As noted bellow, jsonpb is depricated and the new solution is to use protojson

like image 143
michaelbn Avatar answered Oct 13 '22 02:10

michaelbn


I found some of these modules (jsonpb) to be deprecated. What worked for me was the google encoding version:

import "google.golang.org/protobuf/encoding/protojson"

jsonString := protojson.Format(protoMessage)
like image 8
Evan Moran Avatar answered Oct 13 '22 01:10

Evan Moran


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

like image 3
sberry Avatar answered Oct 13 '22 03:10

sberry