add support for pointers to time and if nil put null in json response

This commit is contained in:
Sam Woodard 2015-10-13 09:10:10 -07:00
parent fd92bd51ba
commit 438e9b0626
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) v := reflect.ValueOf(val)
if fieldValue.Type() == reflect.TypeOf(time.Time{}) { if fieldValue.Type() == reflect.TypeOf(time.Time{}) {
var at int64 var at int64
if v.Kind() == reflect.Float64 { if v.Kind() == reflect.Float64 {
@ -173,6 +172,26 @@ func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node)
return false 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 { if fieldValue.Kind() == reflect.Int && v.Kind() == reflect.Float64 {
fieldValue.Set(reflect.ValueOf(int(v.Interface().(float64)))) fieldValue.Set(reflect.ValueOf(int(v.Interface().(float64))))
} else { } else {

View File

@ -203,6 +203,22 @@ func visitModelNode(model interface{}, sideload bool) (*Node, []*Node, error) {
unix := fieldValue.MethodByName("Unix") unix := fieldValue.MethodByName("Unix")
val := unix.Call(make([]reflect.Value, 0))[0] val := unix.Call(make([]reflect.Value, 0))[0]
node.Attributes[args[1]] = val.Int() 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 { } else {
node.Attributes[args[1]] = fieldValue.Interface() node.Attributes[args[1]] = fieldValue.Interface()
} }