[#120] protogen: Omit empty fields from JSON output

Signed-off-by: Evgenii Stratonikov <e.stratonikov@yadro.com>
This commit is contained in:
Evgenii Stratonikov 2024-10-01 09:53:38 +03:00
parent 805da79319
commit eeb754c327
19 changed files with 20 additions and 11 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -147,8 +147,11 @@ func emitJSONMarshal(g *protogen.GeneratedFile, msg *protogen.Message) {
g.P("func (x *", msg.GoIdent.GoName, ") MarshalEasyJSON(out *", jwriterPackage.Ident("Writer"), ") {") g.P("func (x *", msg.GoIdent.GoName, ") MarshalEasyJSON(out *", jwriterPackage.Ident("Writer"), ") {")
g.P(`if x == nil { out.RawString("null"); return }`) g.P(`if x == nil { out.RawString("null"); return }`)
if len(msg.Fields) != 0 {
g.P("first := true")
}
g.P("out.RawByte('{')") g.P("out.RawByte('{')")
for i, f := range msg.Fields { for _, f := range msg.Fields {
if f.Oneof != nil { if f.Oneof != nil {
if f.Oneof.Fields[0] != f { if f.Oneof.Fields[0] != f {
continue continue
@ -157,29 +160,35 @@ func emitJSONMarshal(g *protogen.GeneratedFile, msg *protogen.Message) {
g.P("switch xx := x.", f.Oneof.GoName, ".(type) {") g.P("switch xx := x.", f.Oneof.GoName, ".(type) {")
for _, ff := range f.Oneof.Fields { for _, ff := range f.Oneof.Fields {
g.P("case *", ff.GoIdent, ":") g.P("case *", ff.GoIdent, ":")
emitJSONFieldWrite(g, ff, "xx", i == 0) emitJSONFieldWrite(g, ff, "xx")
} }
g.P("}") g.P("}")
continue continue
} }
emitJSONFieldWrite(g, f, "x", i == 0) emitJSONFieldWrite(g, f, "x")
} }
g.P("out.RawByte('}')") g.P("out.RawByte('}')")
g.P("}") g.P("}")
} }
func emitJSONFieldWrite(g *protogen.GeneratedFile, f *protogen.Field, name string, first bool) { func emitJSONFieldWrite(g *protogen.GeneratedFile, f *protogen.Field, name string) {
g.P("{") g.P("{")
defer g.P("}") defer g.P("}")
g.P("const prefix string = ", `",\"`, fieldJSONName(f), `\":"`)
if first {
g.P("out.RawString(prefix[1:])")
} else {
g.P("out.RawString(prefix)")
}
selector := name + "." + f.GoName selector := name + "." + f.GoName
isNotDefault := notNil
if f.Desc.IsList() {
isNotDefault = notEmpty
} else if f.Desc.Kind() != protoreflect.MessageKind {
_, isNotDefault = easyprotoKindInfo(f.Desc.Kind())
}
g.P("if ", isNotDefault(selector), "{")
defer g.P("}")
g.P("if !first { out.RawByte(','); } else { first = false; }")
g.P("const prefix string = ", `"\"`, fieldJSONName(f), `\":"`)
g.P("out.RawString(prefix)")
if f.Desc.IsList() { if f.Desc.IsList() {
selector += "[i]" selector += "[i]"
g.P("out.RawByte('[')") g.P("out.RawByte('[')")