File tree 2 files changed +38
-0
lines changed
2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -2,6 +2,7 @@ package extra
2
2
3
3
import (
4
4
"github.com/json-iterator/go"
5
+ "strings"
5
6
"unicode"
6
7
)
7
8
@@ -17,6 +18,16 @@ type namingStrategyExtension struct {
17
18
18
19
func (extension * namingStrategyExtension ) UpdateStructDescriptor (structDescriptor * jsoniter.StructDescriptor ) {
19
20
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
+ }
20
31
binding .ToNames = []string {extension .translate (binding .Field .Name ())}
21
32
binding .FromNames = []string {extension .translate (binding .Field .Name ())}
22
33
}
Original file line number Diff line number Diff line change @@ -21,3 +21,30 @@ func Test_lower_case_with_underscores(t *testing.T) {
21
21
should .Nil (err )
22
22
should .Equal (`{"user_name":"taowen","first_language":"Chinese"}` , string (output ))
23
23
}
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
+ }
You can’t perform that action at this time.
0 commit comments