File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -2,6 +2,7 @@ package extra
22
33import  (
44	"github.com/json-iterator/go" 
5+ 	"strings" 
56	"unicode" 
67)
78
@@ -17,6 +18,16 @@ type namingStrategyExtension struct {
1718
1819func  (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	}
Original file line number Diff line number Diff 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+ }
 
 
   
 
     
   
   
          
    
    
     
    
      
     
     
    You can’t perform that action at this time.
  
 
    
  
    
      
        
     
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments