From 1755dd249b0c2d84a2d29b3bf8001afab61f881d Mon Sep 17 00:00:00 2001 From: zm <360475097@qq.com> Date: Sat, 11 Mar 2023 20:08:41 +0800 Subject: [PATCH] add support json tag attribute for StructToMap function (#78) --- convertor/convertor.go | 7 ++++--- convertor/convertor_test.go | 41 +++++++++++++++++++++++++++---------- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/convertor/convertor.go b/convertor/convertor.go index 7df9458..91dad35 100644 --- a/convertor/convertor.go +++ b/convertor/convertor.go @@ -253,10 +253,11 @@ func StructToMap(value any) (map[string]any, error) { for i := 0; i < fieldNum; i++ { name := t.Field(i).Name tag := t.Field(i).Tag.Get("json") - if regex.MatchString(name) && tag != "" { - //result[name] = v.Field(i).Interface() - result[tag] = v.Field(i).Interface() + if tag == "" || strings.HasPrefix(tag, "-") || !regex.MatchString(name) { + continue } + tag = strings.Split(tag, ",")[0] + result[tag] = v.Field(i).Interface() } return result, nil diff --git a/convertor/convertor_test.go b/convertor/convertor_test.go index e9fd172..d73ffee 100644 --- a/convertor/convertor_test.go +++ b/convertor/convertor_test.go @@ -180,18 +180,37 @@ func TestToMap(t *testing.T) { func TestStructToMap(t *testing.T) { assert := internal.NewAssert(t, "TestStructToMap") - type People struct { - Name string `json:"name"` - age int - } - p := People{ - "test", - 100, - } - pm, _ := StructToMap(p) + t.Run("StructToMap", func(t *testing.T) { + type People struct { + Name string `json:"name"` + age int + } + p := People{ + "test", + 100, + } + pm, _ := StructToMap(p) + var expected = map[string]any{"name": "test"} + assert.Equal(expected, pm) + }) - expected := map[string]any{"name": "test"} - assert.Equal(expected, pm) + t.Run("StructToMapWithJsonAttr", func(t *testing.T) { + type People struct { + Name string `json:"name,omitempty"` // json tag with attribute + Phone string `json:"phone"` // json tag without attribute + Sex string `json:"-"` // ignore + age int // no tag + } + p := People{ + "test", + "1111", + "male", + 100, + } + pm, _ := StructToMap(p) + var expected = map[string]any{"name": "test", "phone": "1111"} + assert.Equal(expected, pm) + }) } func TestMapToSlice(t *testing.T) {