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

How to Remove the `omitempty` Tag from Protobuf-Generated JSON?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 13:25:13869browse

How to Remove the `omitempty` Tag from Protobuf-Generated JSON?

Removing the Omitempty Tag from Protocol Buffer-Generated JSON Tags

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!

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