diff --git a/list.go b/list.go index 4938d57..3d72bea 100644 --- a/list.go +++ b/list.go @@ -53,25 +53,25 @@ func (list *List) UnmarshalJSON(rawData []byte) error { /* MarshalJSON returns a top level object for the "data" attribute if a single object. In -all other cases returns a JSON encoded list for "data". +all other cases returns a JSON encoded list for "data". We use a pointer receiver here +so we are able to distinguish between nil (don't serialize) and empty (serialize as []). */ func (list *List) MarshalJSON() ([]byte, error) { // avoid stack overflow by using this subtype for marshaling type MarshalList List - marshalList := (*MarshalList)(list) - isnil := marshalList == nil - count := 0 - if !isnil { - count = len(*marshalList) + + if list == nil { + return nil, nil } + marshalList := MarshalList(*list) + count := len(marshalList) + switch { - case isnil: - return nil, nil case count == 0: return []byte("[]"), nil case count == 1: - return json.Marshal((*marshalList)[0]) + return json.Marshal(marshalList[0]) default: return json.Marshal(marshalList) }