github.com/zhangdapeng520/zdpgo_json@v0.1.5/jsoniter/extra/naming_strategy.go (about) 1 package extra 2 3 import ( 4 "github.com/zhangdapeng520/zdpgo_json/jsoniter" 5 "strings" 6 "unicode" 7 ) 8 9 // SetNamingStrategy rename struct fields uniformly 10 func SetNamingStrategy(translate func(string) string) { 11 jsoniter.RegisterExtension(&namingStrategyExtension{jsoniter.DummyExtension{}, translate}) 12 } 13 14 type namingStrategyExtension struct { 15 jsoniter.DummyExtension 16 translate func(string) string 17 } 18 19 func (extension *namingStrategyExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) { 20 for _, binding := range structDescriptor.Fields { 21 if unicode.IsLower(rune(binding.Field.Name()[0])) || binding.Field.Name()[0] == '_' { 22 continue 23 } 24 tag, hastag := binding.Field.Tag().Lookup("json") 25 if hastag { 26 tagParts := strings.Split(tag, ",") 27 if tagParts[0] == "-" { 28 continue // hidden field 29 } 30 if tagParts[0] != "" { 31 continue // field explicitly named 32 } 33 } 34 binding.ToNames = []string{extension.translate(binding.Field.Name())} 35 binding.FromNames = []string{extension.translate(binding.Field.Name())} 36 } 37 } 38 39 // LowerCaseWithUnderscores one strategy to SetNamingStrategy for. It will change HelloWorld to hello_world. 40 func LowerCaseWithUnderscores(name string) string { 41 newName := []rune{} 42 for i, c := range name { 43 if i == 0 { 44 newName = append(newName, unicode.ToLower(c)) 45 } else { 46 if unicode.IsUpper(c) { 47 newName = append(newName, '_') 48 newName = append(newName, unicode.ToLower(c)) 49 } else { 50 newName = append(newName, c) 51 } 52 } 53 } 54 return string(newName) 55 }