Home >Backend Development >Golang >How to Remove `omitempty` Tags from JSON in Protocol Buffer Structs?

How to Remove `omitempty` Tags from JSON in Protocol Buffer Structs?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 16:45:11995browse

How to Remove `omitempty` Tags from JSON in Protocol Buffer Structs?

How to Remove the Omitempty Tag from Generated JSON Tags in Protocol Buffer Structs

In certain use cases, it may be necessary to remove the omitempty tag from the JSON tags generated for protocol buffer structs. Protocol buffers, especially when used with gRPC, are a powerful tool for data serialization and transfer. However, the inclusion of the omitempty tag can lead to the omission of default or empty values during JSON marshaling, which may not be desirable.

The Problem

When using protocol buffers with a JSON proxy, the generated struct may have omitempty tags included in the JSON tags, as seen in the example below:

message Status {
  int32 code = 1;
  string message = 2;
}

The resulting generated struct:

type Status struct {
  Code int32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"`
  Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
}

The Solution

To remove the omitempty tag from the generated structs, there are two possible approaches:

  1. Using grpc-gateway: If you're using grpc-gateway, you can configure the servemux with the following option:
gwmux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true}))
  1. Using google.golang.org/protobuf/encoding/protojson: For applications outside of grpc-gateway, you can use the google.golang.org/protobuf/encoding/protojson package instead of the standard encoding/json for marshaling. This package provides finer control over the marshaling process, including the ability to emit default values:
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) // You should check for errors here
}

By implementing one of these approaches, you can effectively remove the omitempty tags from the JSON tags generated for your protocol buffer structs, ensuring that default or empty values are included during JSON marshaling.

The above is the detailed content of How to Remove `omitempty` Tags from JSON in Protocol Buffer Structs?. 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