Przeglądaj źródła

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 <herbie@google.com>
Joe Tsai 6 lat temu
rodzic
commit
e5900a6a90

+ 7 - 2
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,

+ 0 - 1
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.