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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
// Package jsonhooks adds hooks that are automatically called before JSON marshaling (PreMarshalJSON) and
// after JSON unmarshaling (PostUnmarshalJSON). It does not do so recursively.
package jsonhooks
import (
"encoding/json"
"reflect"
)
// Marshal wraps encoding/json.Marshal, calls v.PreMarshalJSON() if it exists
func Marshal(v interface{}) ([]byte, error) {
if ImplementsPreJSONMarshaler(v) {
err := v.(PreJSONMarshaler).PreMarshalJSON()
if err != nil {
return nil, err
}
}
return json.Marshal(v)
}
// Unmarshal wraps encoding/json.Unmarshal, calls v.PostUnmarshalJSON() if it exists
func Unmarshal(data []byte, v interface{}) error {
err := json.Unmarshal(data, v)
if err != nil {
return err
}
if ImplementsPostJSONUnmarshaler(v) {
err := v.(PostJSONUnmarshaler).PostUnmarshalJSON()
if err != nil {
return err
}
}
return nil
}
// PreJSONMarshaler infers support for the PreMarshalJSON pre-hook
type PreJSONMarshaler interface {
PreMarshalJSON() error
}
// ImplementsPreJSONMarshaler checks for support for the PreMarshalJSON pre-hook
func ImplementsPreJSONMarshaler(v interface{}) bool {
value := reflect.ValueOf(v)
if !value.IsValid() {
return false
}
_, ok := value.Interface().(PreJSONMarshaler)
return ok
}
// PostJSONUnmarshaler infers support for the PostUnmarshalJSON post-hook
type PostJSONUnmarshaler interface {
PostUnmarshalJSON() error
}
// ImplementsPostJSONUnmarshaler checks for support for the PostUnmarshalJSON post-hook
func ImplementsPostJSONUnmarshaler(v interface{}) bool {
value := reflect.ValueOf(v)
if value.Kind() == reflect.Ptr && value.IsNil() {
return false
}
_, ok := value.Interface().(PostJSONUnmarshaler)
return ok
}
|