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
Release: 2024-11-30 13:25:13
Original
868 people have browsed it

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}))
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template