From 9d087a727cef6968c693e368dfe33b82a0b14265 Mon Sep 17 00:00:00 2001 From: whyrusleeping Date: Fri, 14 Aug 2020 15:24:01 -0700 Subject: [PATCH] add json marshalers to CborTime --- testing/roundtrip_test.go | 15 +++++++++++++++ utils.go | 13 +++++++++++++ 2 files changed, 28 insertions(+) diff --git a/testing/roundtrip_test.go b/testing/roundtrip_test.go index 4bf92e9..fed37c6 100644 --- a/testing/roundtrip_test.go +++ b/testing/roundtrip_test.go @@ -2,6 +2,7 @@ package testing import ( "bytes" + "encoding/json" "math/rand" "reflect" "testing" @@ -146,4 +147,18 @@ func TestTimeIsh(t *testing.T) { t.Fatal("no") } + b, err := json.Marshal(val) + if err != nil { + t.Fatal(err) + } + + var out2 ThingWithSomeTime + if err := json.Unmarshal(b, &out2); err != nil { + t.Fatal(err) + } + + if out2.When != out.When { + t.Fatal(err) + } + } diff --git a/utils.go b/utils.go index 6be5c77..0c97ce5 100644 --- a/utils.go +++ b/utils.go @@ -739,3 +739,16 @@ func (ct *CborTime) UnmarshalCBOR(r io.Reader) error { func (ct CborTime) Time() time.Time { return (time.Time)(ct) } + +func (ct CborTime) MarshalJSON() ([]byte, error) { + return ct.Time().MarshalJSON() +} + +func (ct *CborTime) UnmarshalJSON(b []byte) error { + var t time.Time + if err := t.UnmarshalJSON(b); err != nil { + return err + } + *(*time.Time)(ct) = t + return nil +} -- GitLab