From 8d42e7f328300a85f6ed7a8886befa33e14261ef Mon Sep 17 00:00:00 2001 From: univac490 <31466205+univac490@users.noreply.github.com> Date: Sun, 24 Dec 2023 07:09:48 -0800 Subject: [PATCH] Compatibilty with JSON tags (#143) --- internal/encoding.go | 19 ++++++++++++++++++- internal/encoding_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/internal/encoding.go b/internal/encoding.go index e01823b..5b57d87 100644 --- a/internal/encoding.go +++ b/internal/encoding.go @@ -173,10 +173,27 @@ func createRenameMap(rv reflect.Value) map[string]string { for i := 0; i < rv.NumField(); i++ { fieldType := rv.Type().Field(i) + renameTo := fieldType.Name + renameFrom := fieldType.Name + + jsonTagStr, found := fieldType.Tag.Lookup("json") + if found { + name, _ := processStructTag(jsonTagStr) + if name != "" { + renameTo = name + } + } + tagStr, found := fieldType.Tag.Lookup("clover") if found { name, _ := processStructTag(tagStr) - renameMap[name] = fieldType.Name + if name != "" { + renameFrom = name + } + } + + if renameFrom != renameTo { + renameMap[renameFrom] = renameTo } } return renameMap diff --git a/internal/encoding_test.go b/internal/encoding_test.go index eeaa253..453f60e 100644 --- a/internal/encoding_test.go +++ b/internal/encoding_test.go @@ -26,6 +26,17 @@ type TestStruct struct { Data []byte `clover:",omitempty"` } +type TestStruct2 struct { + BaseModel + IntField int `clover:"int_field,omitempty"` + UintField uint `clover:"uint,omitempty" json:"uint_field"` + StringField string + FloatField float32 `clover:",omitempty" json:"float_field"` + BoolField bool `clover:"bool_field,omitempty" json:"bool_field"` + TimeField time.Time `clover:",omitempty"` + Data []byte `clover:",omitempty"` +} + func TestNormalize(t *testing.T) { date := time.Date(2020, 01, 1, 0, 0, 0, 0, time.UTC) @@ -132,3 +143,29 @@ func TestEncodeDecode(t *testing.T) { require.Equal(t, m, norm) } + +func TestJsonTag(t *testing.T) { + date := time.Date(2020, 01, 1, 0, 0, 0, 0, time.UTC) + + s := &TestStruct2{ + TimeField: date, + UintField: 100, + IntField: 200, + FloatField: 300, + StringField: "json", + BoolField: true, + } + + normalized, err := Normalize(s) + require.NoError(t, err) + + require.IsType(t, normalized, map[string]interface{}{}) + fields, _ := normalized.(map[string]interface{}) + require.NotNil(t, fields) + + var ns TestStruct2 + err = Convert(fields, &ns) + require.NoError(t, err) + + require.Equal(t, s, &ns) +} \ No newline at end of file