go-json/struct_field.go

61 lines
1.0 KiB
Go
Raw Normal View History

2020-08-20 06:38:50 +03:00
package json
import (
"reflect"
"strings"
)
func getTag(field reflect.StructField) string {
return field.Tag.Get("json")
}
func isIgnoredStructField(field reflect.StructField) bool {
if field.PkgPath != "" && !field.Anonymous {
// private field
return true
}
tag := getTag(field)
if tag == "-" {
return true
}
return false
}
type structTag struct {
key string
2020-08-22 09:40:18 +03:00
isTaggedKey bool
2020-08-20 06:38:50 +03:00
isOmitEmpty bool
isString bool
2020-08-22 06:58:34 +03:00
field reflect.StructField
}
type structTags []*structTag
func (t structTags) existsKey(key string) bool {
for _, tt := range t {
if tt.key == key {
return true
}
}
return false
2020-08-20 06:38:50 +03:00
}
func structTagFromField(field reflect.StructField) *structTag {
keyName := field.Name
tag := getTag(field)
2020-08-22 09:40:18 +03:00
st := &structTag{field: field}
2020-08-20 06:38:50 +03:00
opts := strings.Split(tag, ",")
if len(opts) > 0 {
if opts[0] != "" {
keyName = opts[0]
2020-08-22 09:40:18 +03:00
st.isTaggedKey = true
2020-08-20 06:38:50 +03:00
}
}
2020-08-22 09:40:18 +03:00
st.key = keyName
2020-08-20 06:38:50 +03:00
if len(opts) > 1 {
st.isOmitEmpty = opts[1] == "omitempty"
st.isString = opts[1] == "string"
}
return st
}