From e5900a6a906dc311a3d90e986a7e5aaf149e974d Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Tue, 9 Jul 2019 13:31:02 -0700 Subject: [PATCH] internal/encoding/tag: fix handling of JSON name When decoding, only treat the name as being explicitly set if the name differs from what the JSON name would have been had it been automatically derived from the protobuf field name. Change-Id: Ida9256eafe7af20c7a06be2d4fb298be44276104 Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/185398 Reviewed-by: Herbie Ong --- internal/encoding/tag/tag.go | 9 +++++++-- internal/encoding/tag/tag_test.go | 1 - 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/internal/encoding/tag/tag.go b/internal/encoding/tag/tag.go index 1c568e3e..80e8488b 100644 --- a/internal/encoding/tag/tag.go +++ b/internal/encoding/tag/tag.go @@ -13,6 +13,7 @@ import ( defval "google.golang.org/protobuf/internal/encoding/defval" fdesc "google.golang.org/protobuf/internal/filedesc" + "google.golang.org/protobuf/internal/strs" pref "google.golang.org/protobuf/reflect/protoreflect" ) @@ -101,7 +102,10 @@ func Unmarshal(tag string, goType reflect.Type, evs pref.EnumValueDescriptors) p case strings.HasPrefix(s, "enum="): f.L1.Kind = pref.EnumKind case strings.HasPrefix(s, "json="): - f.L1.JSONName = fdesc.JSONName(s[len("json="):]) + jsonName := s[len("json="):] + if jsonName != strs.JSONCamelCase(string(f.L0.FullName.Name())) { + f.L1.JSONName = fdesc.JSONName(jsonName) + } case s == "packed": f.L1.HasPacked = true f.L1.IsPacked = true @@ -176,7 +180,8 @@ func Marshal(fd pref.FieldDescriptor, enumName string) string { } tag = append(tag, "name="+name) if jsonName := fd.JSONName(); jsonName != "" && jsonName != name && !fd.IsExtension() { - // TODO: The jsonName != name condition looks wrong. + // NOTE: The jsonName != name condition is suspect, but it preserve + // the exact same semantics from the previous generator. tag = append(tag, "json="+jsonName) } // The previous implementation does not tag extension fields as proto3, diff --git a/internal/encoding/tag/tag_test.go b/internal/encoding/tag/tag_test.go index 680ba528..9f22521d 100644 --- a/internal/encoding/tag/tag_test.go +++ b/internal/encoding/tag/tag_test.go @@ -22,7 +22,6 @@ func Test(t *testing.T) { fd.L1.Number = 1337 fd.L1.Cardinality = pref.Repeated fd.L1.Kind = pref.BytesKind - fd.L1.JSONName = fdesc.JSONName("fooField") fd.L1.Default = fdesc.DefaultValue(pref.ValueOf([]byte("hello, \xde\xad\xbe\xef\n")), nil) // Marshal test.