Merge pull request #17 from shwoodard/nil-times

add support for pointers to time and if nil put null in json response
This commit is contained in:
Sam Woodard 2015-10-27 09:26:49 -07:00
commit 53c7c4e5b5
2 changed files with 36 additions and 1 deletions

View File

@ -154,7 +154,6 @@ func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node)
v := reflect.ValueOf(val)
if fieldValue.Type() == reflect.TypeOf(time.Time{}) {
var at int64
if v.Kind() == reflect.Float64 {
@ -173,6 +172,26 @@ func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node)
return false
}
if fieldValue.Type() == reflect.TypeOf(new(time.Time)) {
var at int64
if v.Kind() == reflect.Float64 {
at = int64(v.Interface().(float64))
} else if v.Kind() == reflect.Int {
at = v.Int()
} else {
er = errors.New("Only numbers can be parsed as dates, unix timestamps")
return false
}
v := time.Unix(at, 0)
t := &v
fieldValue.Set(reflect.ValueOf(t))
return false
}
if fieldValue.Kind() == reflect.Int && v.Kind() == reflect.Float64 {
fieldValue.Set(reflect.ValueOf(int(v.Interface().(float64))))
} else {

View File

@ -203,6 +203,22 @@ func visitModelNode(model interface{}, sideload bool) (*Node, []*Node, error) {
unix := fieldValue.MethodByName("Unix")
val := unix.Call(make([]reflect.Value, 0))[0]
node.Attributes[args[1]] = val.Int()
} else if fieldValue.Type() == reflect.TypeOf(new(time.Time)) {
// A time pointer may be nil
t := reflect.ValueOf(fieldValue.Interface())
if t.IsNil() {
node.Attributes[args[1]] = nil
} else {
isZeroMethod := fieldValue.MethodByName("IsZero")
isZero := isZeroMethod.Call(make([]reflect.Value, 0))[0].Interface().(bool)
if isZero {
return false
}
unix := fieldValue.MethodByName("Unix")
val := unix.Call(make([]reflect.Value, 0))[0]
node.Attributes[args[1]] = val.Int()
}
} else {
node.Attributes[args[1]] = fieldValue.Interface()
}