Skip to content

Commit

Permalink
Supporting dynamic data response for single object
Browse files Browse the repository at this point in the history
  • Loading branch information
Derek Dowling committed Jan 8, 2016
1 parent be9c9f4 commit e3c1cc5
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions list.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ interface.
func (list *List) UnmarshalJSON(rawData []byte) error {
// Create a sub-type here so when we call Unmarshal below, we don't recursively
// call this function over and over
type MarshalList List
type UnmarshalList List

// if our "List" is a single object, modify the JSON to make it into a list
// by wrapping with "[ ]"
if rawData[0] == '{' {
rawData = []byte(fmt.Sprintf("[%s]", rawData))
}

newList := MarshalList{}
newList := UnmarshalList{}

err := json.Unmarshal(rawData, &newList)
if err != nil {
Expand All @@ -50,3 +50,21 @@ func (list *List) UnmarshalJSON(rawData []byte) error {

return nil
}

/*
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) {
// avoid stack overflow by using this subtype for marshaling
type MarshalList List
marshalList := MarshalList(list)
count := len(marshalList)

switch {
case count == 1:
return json.Marshal(marshalList[0])
default:
return json.Marshal(marshalList)
}
}

0 comments on commit e3c1cc5

Please sign in to comment.