2016-08-26 20:32:04 +00:00
|
|
|
package serializer
|
2016-02-15 18:09:10 +00:00
|
|
|
|
2016-02-13 01:54:50 +00:00
|
|
|
import (
|
|
|
|
"reflect"
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
2016-08-27 05:10:15 +00:00
|
|
|
"fmt"
|
2016-02-13 01:54:50 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type JsonSerializer struct {
|
|
|
|
types map[string]reflect.Type
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewJsonSerializer(types ...interface{}) *JsonSerializer {
|
|
|
|
s := &JsonSerializer{make(map[string]reflect.Type)}
|
|
|
|
for _, t := range types {
|
|
|
|
s.RegisterType(t)
|
|
|
|
}
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
|
|
|
func (me *JsonSerializer) RegisterType(t interface{}) {
|
|
|
|
type_ := reflect.TypeOf(t)
|
|
|
|
if type_.Kind() == reflect.Ptr || type_.Kind() == reflect.Interface {
|
|
|
|
type_ = type_.Elem()
|
|
|
|
}
|
|
|
|
me.types[type_.String()] = type_
|
|
|
|
}
|
|
|
|
|
2016-02-18 02:15:40 +00:00
|
|
|
func (me *JsonSerializer) Serialize(obj interface{}) ([]byte, string, error) {
|
2016-08-27 05:10:15 +00:00
|
|
|
if obj == nil {
|
|
|
|
return []byte(""), "", nil
|
|
|
|
}
|
2016-02-13 01:54:50 +00:00
|
|
|
type_ := reflect.TypeOf(obj)
|
|
|
|
if (type_.Kind() == reflect.Interface || type_.Kind() == reflect.Ptr) {
|
2016-02-18 02:15:40 +00:00
|
|
|
return nil, "", errors.New("Trying to serialize a Ptr type.")
|
2016-02-13 01:54:50 +00:00
|
|
|
}
|
|
|
|
typeId := type_.String()
|
|
|
|
data, err := json.Marshal(obj)
|
|
|
|
if err != nil {
|
2016-02-18 02:15:40 +00:00
|
|
|
return nil, "", err
|
2016-02-13 01:54:50 +00:00
|
|
|
}
|
2016-02-18 02:15:40 +00:00
|
|
|
return data, typeId, nil
|
2016-02-13 01:54:50 +00:00
|
|
|
}
|
|
|
|
|
2016-02-18 02:15:40 +00:00
|
|
|
func (me *JsonSerializer) Deserialize(serialized []byte, typeId string) (interface{}, error) {
|
2016-08-27 05:10:15 +00:00
|
|
|
if (typeId == "") {
|
|
|
|
return nil, nil
|
|
|
|
}
|
2016-02-13 01:54:50 +00:00
|
|
|
type_ := me.types[typeId]
|
|
|
|
if type_ == nil {
|
2016-08-27 05:10:15 +00:00
|
|
|
return nil, errors.New(fmt.Sprintf("type %q not registered in serializer", typeId))
|
2016-02-13 01:54:50 +00:00
|
|
|
}
|
|
|
|
objPtr := reflect.New(type_).Interface()
|
2016-02-18 02:15:40 +00:00
|
|
|
err := json.Unmarshal(serialized, objPtr)
|
2016-02-13 01:54:50 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
obj := reflect.Indirect(reflect.ValueOf(objPtr)).Interface()
|
|
|
|
return obj, nil
|
|
|
|
}
|