mirror of
https://github.com/json-iterator/go.git
synced 2024-11-27 08:30:57 +02:00
fix #276 allow rename when set naming strategy
This commit is contained in:
parent
2fbdfbb595
commit
ab8a2e0c74
@ -2,6 +2,7 @@ package extra
|
||||
|
||||
import (
|
||||
"github.com/json-iterator/go"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
@ -17,6 +18,16 @@ type namingStrategyExtension struct {
|
||||
|
||||
func (extension *namingStrategyExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {
|
||||
for _, binding := range structDescriptor.Fields {
|
||||
tag, hastag := binding.Field.Tag().Lookup("json")
|
||||
if hastag {
|
||||
tagParts := strings.Split(tag, ",")
|
||||
if tagParts[0] == "-" {
|
||||
continue // hidden field
|
||||
}
|
||||
if tagParts[0] != "" {
|
||||
continue // field explicitly named
|
||||
}
|
||||
}
|
||||
binding.ToNames = []string{extension.translate(binding.Field.Name())}
|
||||
binding.FromNames = []string{extension.translate(binding.Field.Name())}
|
||||
}
|
||||
|
@ -21,3 +21,30 @@ func Test_lower_case_with_underscores(t *testing.T) {
|
||||
should.Nil(err)
|
||||
should.Equal(`{"user_name":"taowen","first_language":"Chinese"}`, string(output))
|
||||
}
|
||||
|
||||
func Test_set_naming_strategy_with_overrides(t *testing.T) {
|
||||
should := require.New(t)
|
||||
SetNamingStrategy(LowerCaseWithUnderscores)
|
||||
output, err := jsoniter.Marshal(struct {
|
||||
UserName string `json:"UserName"`
|
||||
FirstLanguage string
|
||||
}{
|
||||
UserName: "taowen",
|
||||
FirstLanguage: "Chinese",
|
||||
})
|
||||
should.Nil(err)
|
||||
should.Equal(`{"UserName":"taowen","first_language":"Chinese"}`, string(output))
|
||||
}
|
||||
|
||||
func Test_set_naming_strategy_with_omitempty(t *testing.T) {
|
||||
should := require.New(t)
|
||||
SetNamingStrategy(LowerCaseWithUnderscores)
|
||||
output, err := jsoniter.Marshal(struct {
|
||||
UserName string
|
||||
FirstLanguage string `json:",omitempty"`
|
||||
}{
|
||||
UserName: "taowen",
|
||||
})
|
||||
should.Nil(err)
|
||||
should.Equal(`{"user_name":"taowen"}`, string(output))
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user