Home >Backend Development >Golang >How to Remove the `omitempty` Tag from Protobuf-Generated JSON?
Introduction
Protocol Buffers (Protobuf) is a language-neutral, platform-neutral extensible mechanism for serializing structured data. When working with Protobuf, it may be necessary to remove the omitempty tag from JSON tags generated in the *.pb.go files. This article explores how to accomplish this using various methods.
grpc-gateway Option
If utilizing grpc-gateway, including the following option when creating the ServeMux will ensure that default values are present during JSON marshaling:
gwmux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true}))
protobuf Package
Outside of grpc-gateway, the google.golang.org/protobuf/encoding/protojson package (now replacing the deprecated github.com/golang/protobuf/jsonpb) can be employed to marshal Protocol Buffer messages. By utilizing the Marshaler struct with EmitDefaults: true set, default values will be included in the JSON output:
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) // Error handling omitted }
The above is the detailed content of How to Remove the `omitempty` Tag from Protobuf-Generated JSON?. For more information, please follow other related articles on the PHP Chinese website!