diff --git a/response.go b/response.go index d83717a..76ef78e 100644 --- a/response.go +++ b/response.go @@ -123,6 +123,12 @@ func visitModelNode(model interface{}, sideload bool) (*JsonApiNode, []*JsonApiN if len(args) >= 2 { if fieldValue.Type() == reflect.TypeOf(time.Time{}) { + 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() diff --git a/response_test.go b/response_test.go index 7b69839..1ec5127 100644 --- a/response_test.go +++ b/response_test.go @@ -102,6 +102,29 @@ func TestSupportsAttributes(t *testing.T) { } } +func TestOmitsZeroTimes(t *testing.T) { + testModel := &Blog{ + Id: 5, + Title: "Title 1", + CreatedAt: time.Time{}, + } + + resp, err := MarshalJsonApiOnePayload(testModel) + if err != nil { + t.Fatal(err) + } + + response := resp.Data + + if response.Attributes == nil { + t.Fatalf("Expected attributes") + } + + if response.Attributes["created_at"] != nil { + t.Fatalf("Created at was serialized even though it was a zero Time") + } +} + func TestRelations(t *testing.T) { testModel := &Blog{ Id: 5,