Skip to content

Commit

Permalink
Serialize empty data as empty array
Browse files Browse the repository at this point in the history
  • Loading branch information
Peter Grant committed Feb 19, 2016
1 parent 980176b commit f87157a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
6 changes: 3 additions & 3 deletions document.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down Expand Up @@ -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 {
Expand Down
16 changes: 12 additions & 4 deletions list.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down

0 comments on commit f87157a

Please sign in to comment.