Home >Backend Development >Golang >How to Remove `omitempty` Tags from Protobuf-Generated JSON?
Removing Omitempty Tags from Protobuf-Generated JSON
When generating Protobuf classes for use with a JSON proxy, you may encounter the omitempty tags on the generated structs. These tags suppress empty fields during JSON marshaling, which can be undesirable in certain scenarios.
To remove the omitempty tags from the generated structs:
Using grpc-gateway
If you're using grpc-gateway, you can disable the omitempty behavior by specifying the following option when creating your servemux:
gwmux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true}))
Outside of grpc-gateway
To marshal your Protobuf message without the omitempty behavior outside of grpc-gateway, use the google.golang.org/protobuf/encoding/protojson package instead of the standard encoding/json package:
func sendProtoMessage(resp proto.Message, w http.ResponseWriter) { w.Header().Set("Content-Type", "application/json; charset=utf-8") m := protojson.Marshaler{EmitDefaults: true} m.Marshal(w, resp) // Check for errors here }
Note:
The above is the detailed content of How to Remove `omitempty` Tags from Protobuf-Generated JSON?. For more information, please follow other related articles on the PHP Chinese website!