Skip to content

Commit 2a2f105

Browse files
authored
Merge pull request #158 from swordqiu/hotfix/qj-field-tag-name-json
fix: field tag name allow alter name
2 parents 638d1d4 + b4131a0 commit 2a2f105

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

util/reflectutils/jsonfield.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ type SStructFieldInfo struct {
4747
kebabFieldName string
4848
ForceString bool
4949
Tags map[string]string
50+
51+
Aliases []string
5052
}
5153

5254
func (s *SStructFieldInfo) updateTags(k, v string) {
@@ -69,6 +71,9 @@ func (s SStructFieldInfo) deepCopy() *SStructFieldInfo {
6971
tags[k] = v
7072
}
7173
scopy.Tags = tags
74+
aliases := make([]string, len(s.Aliases))
75+
copy(aliases, s.Aliases)
76+
scopy.Aliases = aliases
7277
return &scopy
7378
}
7479

@@ -125,6 +130,9 @@ func ParseFieldJsonInfo(name string, tag reflect.StructTag) SStructFieldInfo {
125130
if !info.Ignore && len(info.Name) == 0 {
126131
info.Name = info.kebabFieldName
127132
}
133+
if val, ok := info.Tags["alias"]; !info.Ignore && ok {
134+
info.Aliases = strings.Split(val, ",")
135+
}
128136
return info
129137
}
130138

@@ -336,6 +344,8 @@ func (fields SStructFieldValueSet) GetStructFieldIndexes2(name string, strictMod
336344
ret = append(ret, i)
337345
} else if info.FieldName == capName {
338346
ret = append(ret, i)
347+
} else if len(info.Aliases) > 0 && utils.IsInArray(name, info.Aliases) {
348+
ret = append(ret, i)
339349
}
340350
}
341351
}

util/reflectutils/jsonfield_test.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,3 +455,51 @@ func TestEmbededStructPtr(t *testing.T) {
455455
}
456456
}
457457
}
458+
459+
func TestAliases(t *testing.T) {
460+
type Struct1 struct {
461+
Field1 string `json:"field1" alias:"field1_alias"`
462+
}
463+
type Struct2 struct {
464+
Field2 string `json:"field2" alias:"field2_alias"`
465+
}
466+
type TopStruct struct {
467+
Struct1
468+
Struct2
469+
}
470+
471+
cases := []struct {
472+
val interface{}
473+
name string
474+
index int
475+
}{
476+
{
477+
val: TopStruct{},
478+
name: "field1",
479+
index: 0,
480+
},
481+
{
482+
val: TopStruct{},
483+
name: "field2",
484+
index: 1,
485+
},
486+
{
487+
val: TopStruct{},
488+
name: "field1_alias",
489+
index: 0,
490+
},
491+
{
492+
val: TopStruct{},
493+
name: "field2_alias",
494+
index: 1,
495+
},
496+
}
497+
498+
for _, c := range cases {
499+
set := FetchStructFieldValueSet(reflect.ValueOf(c.val))
500+
got := set.GetStructFieldIndex(c.name)
501+
if got != c.index {
502+
t.Errorf("Got: %v Want: %v", got, c.index)
503+
}
504+
}
505+
}

0 commit comments

Comments
 (0)