Skip to content

Commit ab8a2e0

Browse files
committed
fix #276 allow rename when set naming strategy
1 parent 2fbdfbb commit ab8a2e0

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

extra/naming_strategy.go

+11
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package extra
22

33
import (
44
"github.com/json-iterator/go"
5+
"strings"
56
"unicode"
67
)
78

@@ -17,6 +18,16 @@ type namingStrategyExtension struct {
1718

1819
func (extension *namingStrategyExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {
1920
for _, binding := range structDescriptor.Fields {
21+
tag, hastag := binding.Field.Tag().Lookup("json")
22+
if hastag {
23+
tagParts := strings.Split(tag, ",")
24+
if tagParts[0] == "-" {
25+
continue // hidden field
26+
}
27+
if tagParts[0] != "" {
28+
continue // field explicitly named
29+
}
30+
}
2031
binding.ToNames = []string{extension.translate(binding.Field.Name())}
2132
binding.FromNames = []string{extension.translate(binding.Field.Name())}
2233
}

extra/naming_strategy_test.go

+27
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,30 @@ func Test_lower_case_with_underscores(t *testing.T) {
2121
should.Nil(err)
2222
should.Equal(`{"user_name":"taowen","first_language":"Chinese"}`, string(output))
2323
}
24+
25+
func Test_set_naming_strategy_with_overrides(t *testing.T) {
26+
should := require.New(t)
27+
SetNamingStrategy(LowerCaseWithUnderscores)
28+
output, err := jsoniter.Marshal(struct {
29+
UserName string `json:"UserName"`
30+
FirstLanguage string
31+
}{
32+
UserName: "taowen",
33+
FirstLanguage: "Chinese",
34+
})
35+
should.Nil(err)
36+
should.Equal(`{"UserName":"taowen","first_language":"Chinese"}`, string(output))
37+
}
38+
39+
func Test_set_naming_strategy_with_omitempty(t *testing.T) {
40+
should := require.New(t)
41+
SetNamingStrategy(LowerCaseWithUnderscores)
42+
output, err := jsoniter.Marshal(struct {
43+
UserName string
44+
FirstLanguage string `json:",omitempty"`
45+
}{
46+
UserName: "taowen",
47+
})
48+
should.Nil(err)
49+
should.Equal(`{"user_name":"taowen"}`, string(output))
50+
}

0 commit comments

Comments
 (0)