From f87157aecd947c2b9f8e71641bf5bc1d42603352 Mon Sep 17 00:00:00 2001 From: Peter Grant Date: Fri, 19 Feb 2016 10:32:33 -0800 Subject: [PATCH] Serialize empty data as empty array --- document.go | 6 +++--- list.go | 16 ++++++++++++---- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/document.go b/document.go index fbaa21f..642a451 100644 --- a/document.go +++ b/document.go @@ -12,7 +12,7 @@ Refer to the JSON API Specification for a full descriptor of each attribute: http://jsonapi.org/format/#document-structure */ type Document struct { - Data List `json:"data,omitempty"` + Data List `json:"data"` Errors ErrorList `json:"errors,omitempty"` Links *Link `json:"links,omitempty"` Included []*Object `json:"included,omitempty"` @@ -89,10 +89,10 @@ func (d *Document) Validate(r *http.Request, response bool) *Error { return nil } - if !d.HasErrors() && !d.HasData() { + if !d.HasErrors() && d.Data == nil { return ISE("Both `errors` and `data` cannot be blank for a JSON response") } - if d.HasErrors() && d.HasData() { + if d.HasErrors() && d.Data != nil { return ISE("Both `errors` and `data` cannot be set for a JSON response") } if !d.HasData() && d.Included != nil { diff --git a/list.go b/list.go index 2070ba4..4938d57 100644 --- a/list.go +++ b/list.go @@ -55,15 +55,23 @@ 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". */ -func (list List) MarshalJSON() ([]byte, error) { +func (list *List) MarshalJSON() ([]byte, error) { // avoid stack overflow by using this subtype for marshaling type MarshalList List - marshalList := MarshalList(list) - count := len(marshalList) + marshalList := (*MarshalList)(list) + isnil := marshalList == nil + count := 0 + if !isnil { + 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) }