File tree 1 file changed +20
-2
lines changed
1 file changed +20
-2
lines changed Original file line number Diff line number Diff line change @@ -30,15 +30,15 @@ interface.
30
30
func (list * List ) UnmarshalJSON (rawData []byte ) error {
31
31
// Create a sub-type here so when we call Unmarshal below, we don't recursively
32
32
// call this function over and over
33
- type MarshalList List
33
+ type UnmarshalList List
34
34
35
35
// if our "List" is a single object, modify the JSON to make it into a list
36
36
// by wrapping with "[ ]"
37
37
if rawData [0 ] == '{' {
38
38
rawData = []byte (fmt .Sprintf ("[%s]" , rawData ))
39
39
}
40
40
41
- newList := MarshalList {}
41
+ newList := UnmarshalList {}
42
42
43
43
err := json .Unmarshal (rawData , & newList )
44
44
if err != nil {
@@ -50,3 +50,21 @@ func (list *List) UnmarshalJSON(rawData []byte) error {
50
50
51
51
return nil
52
52
}
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
+ }
You can’t perform that action at this time.
0 commit comments