From 7e34f73bfd2b0391cc6672de94d0ba27132b625f Mon Sep 17 00:00:00 2001 From: Wilhelm Murdoch Date: Fri, 1 Apr 2022 17:55:19 +1000 Subject: [PATCH] Implement the marshaler interface so collections can be easily unmashaled into valid JSON --- collection.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/collection.go b/collection.go index fe5b54d..19356f1 100644 --- a/collection.go +++ b/collection.go @@ -1,6 +1,8 @@ package collection import ( + "bytes" + "encoding/json" "math/rand" "reflect" "time" @@ -354,3 +356,16 @@ func (c *Collection[T]) CountBy(f func(T) bool) (count int) { } return } + +// MarshalJSON implements the Marshaler interface so the current collection's +// items can be marshalled into valid JSON. +func (c *Collection[T]) MarshalJSON() ([]byte, error) { + var buffer bytes.Buffer + encoder := json.NewEncoder(&buffer) + + if err := encoder.Encode(c.Items()); err != nil { + return nil, err + } + + return buffer.Bytes(), nil +}