...
1 package extra
2
3 import (
4 "github.com/json-iterator/go"
5 "strings"
6 "unicode"
7 )
8
9
10 func SupportPrivateFields() {
11 jsoniter.RegisterExtension(&privateFieldsExtension{})
12 }
13
14 type privateFieldsExtension struct {
15 jsoniter.DummyExtension
16 }
17
18 func (extension *privateFieldsExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {
19 for _, binding := range structDescriptor.Fields {
20 isPrivate := unicode.IsLower(rune(binding.Field.Name()[0]))
21 if isPrivate {
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
32 }
33 }
34 }
35
36 func calcFieldNames(originalFieldName string, tagProvidedFieldName string, wholeTag string) []string {
37
38 if wholeTag == "-" {
39 return []string{}
40 }
41
42 var fieldNames []string
43 if tagProvidedFieldName == "" {
44 fieldNames = []string{originalFieldName}
45 } else {
46 fieldNames = []string{tagProvidedFieldName}
47 }
48
49 isNotExported := unicode.IsLower(rune(originalFieldName[0]))
50 if isNotExported {
51 fieldNames = []string{}
52 }
53 return fieldNames
54 }
55
View as plain text