-
Notifications
You must be signed in to change notification settings - Fork 1
/
json.go
41 lines (35 loc) · 913 Bytes
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package types
import (
"encoding"
"encoding/json"
"reflect"
)
var (
jsonMarshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
emptyInterfaceTye = reflect.TypeOf((*interface{})(nil)).Elem()
)
// CanMarshalJSON returns if a type can be marshalled as JSON
func CanMarshalJSON(t reflect.Type) bool {
if t == emptyInterfaceTye {
return true
}
if t.Implements(jsonMarshalerType) {
return true
}
kind := t.Kind()
if kind != reflect.Pointer && reflect.PointerTo(t).Implements(jsonMarshalerType) {
return true
}
if t.Implements(textMarshalerType) {
return true
}
if kind != reflect.Pointer && reflect.PointerTo(t).Implements(textMarshalerType) {
return true
}
if kind == reflect.Pointer {
t = t.Elem()
kind = t.Kind()
}
return kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice
}