Skip to content

Commit e3c1cc5

Browse files
author
Derek Dowling
committed
Supporting dynamic data response for single object
1 parent be9c9f4 commit e3c1cc5

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

list.go

+20-2
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,15 @@ interface.
3030
func (list *List) UnmarshalJSON(rawData []byte) error {
3131
// Create a sub-type here so when we call Unmarshal below, we don't recursively
3232
// call this function over and over
33-
type MarshalList List
33+
type UnmarshalList List
3434

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

41-
newList := MarshalList{}
41+
newList := UnmarshalList{}
4242

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

5151
return nil
5252
}
53+
54+
/*
55+
MarshalJSON returns a top level object for the "data" attribute if a single object. In
56+
all other cases returns a JSON encoded list for "data".
57+
*/
58+
func (list List) MarshalJSON() ([]byte, error) {
59+
// avoid stack overflow by using this subtype for marshaling
60+
type MarshalList List
61+
marshalList := MarshalList(list)
62+
count := len(marshalList)
63+
64+
switch {
65+
case count == 1:
66+
return json.Marshal(marshalList[0])
67+
default:
68+
return json.Marshal(marshalList)
69+
}
70+
}

0 commit comments

Comments
 (0)