Home >Backend Development >Golang >How to Remove `omitempty` Tags from Protobuf-Generated JSON?

How to Remove `omitempty` Tags from Protobuf-Generated JSON?

Linda Hamilton
Linda HamiltonOriginal
2024-11-30 13:04:11796browse

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 google.golang.org/protobuf package replaces the deprecated github.com/golang/protobuf and its jsonpb package.
  • The EmitDefaults option ensures that empty fields are included in the JSON output.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn