grpc-gateway removed omitempty tag from generated json tags, but empty fields are still not returned

1.1k Views Asked by At

I am using grpc-gateway v1.16 and I have removed the omitempty tags from the struct generated in the *.pb.go files as suggested here -> golang protobuf remove omitempty tag from generated json tags

However, I see the empty fields are still not returned in the response.

I have used reflect package and ensured that omitempty tag is not set.

I dont have an option to use some thing like as shown below as that is applicable for all fields.

gwmux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true}))

How can I achieve this?

Thanks in advance

1

There are 1 best solutions below

0
刘沙河 On

This demo runtime version is v1, but your version is v2.

gwmux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true}))

(*) google.golang.org/protobuf replaces the now deprecated github.com/golang/protobuf and its jsonpb package.

runtime v2

import (
  "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
  "google.golang.org/protobuf/encoding/protojson"
)

gwMux := runtime.NewServeMux(
  runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{
    MarshalOptions: protojson.MarshalOptions{
      EmitUnpopulated: true,
    },
  }),
)