Skip to content

Commit

Permalink
Compatibilty with JSON tags (#143)
Browse files Browse the repository at this point in the history
  • Loading branch information
univac490 authored Dec 24, 2023
1 parent aa688ad commit 8d42e7f
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
19 changes: 18 additions & 1 deletion internal/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 37 additions & 0 deletions internal/encoding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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)
}

0 comments on commit 8d42e7f

Please sign in to comment.