Home >Backend Development >Golang >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:
gwmux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true}))
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!