Skip to content

Commit f246f80

Browse files
committed
fix #260, support rename for extra.SupportPrivateFields
1 parent 51dd703 commit f246f80

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

extra/privat_fields.go

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package extra
33
import (
44
"github.com/json-iterator/go"
55
"unicode"
6+
"strings"
67
)
78

89
// SupportPrivateFields include private fields when encoding/decoding
@@ -18,8 +19,37 @@ func (extension *privateFieldsExtension) UpdateStructDescriptor(structDescriptor
1819
for _, binding := range structDescriptor.Fields {
1920
isPrivate := unicode.IsLower(rune(binding.Field.Name()[0]))
2021
if isPrivate {
21-
binding.FromNames = []string{binding.Field.Name()}
22-
binding.ToNames = []string{binding.Field.Name()}
22+
tag, hastag := binding.Field.Tag().Lookup("json")
23+
if !hastag {
24+
binding.FromNames = []string{binding.Field.Name()}
25+
binding.ToNames = []string{binding.Field.Name()}
26+
continue
27+
}
28+
tagParts := strings.Split(tag, ",")
29+
names := calcFieldNames(binding.Field.Name(), tagParts[0], tag)
30+
binding.FromNames = names
31+
binding.ToNames = names
2332
}
2433
}
2534
}
35+
36+
func calcFieldNames(originalFieldName string, tagProvidedFieldName string, wholeTag string) []string {
37+
// ignore?
38+
if wholeTag == "-" {
39+
return []string{}
40+
}
41+
// rename?
42+
var fieldNames []string
43+
if tagProvidedFieldName == "" {
44+
fieldNames = []string{originalFieldName}
45+
} else {
46+
fieldNames = []string{tagProvidedFieldName}
47+
}
48+
// private?
49+
isNotExported := unicode.IsLower(rune(originalFieldName[0]))
50+
if isNotExported {
51+
fieldNames = []string{}
52+
}
53+
return fieldNames
54+
}
55+

0 commit comments

Comments
 (0)