-
Notifications
You must be signed in to change notification settings - Fork 3
/
includes.go
71 lines (60 loc) · 1.66 KB
/
includes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package patreon
import (
"encoding/json"
"fmt"
)
// Includes wraps 'includes' JSON field to handle objects of different type within an array.
type Includes struct {
Items []interface{}
}
// UnmarshalJSON deserializes 'includes' field into the appropriate structs depending on the 'type' field.
// See http://gregtrowbridge.com/golang-json-serialization-with-interfaces/ for implementation details.
func (i *Includes) UnmarshalJSON(b []byte) error {
var items []*json.RawMessage
if err := json.Unmarshal(b, &items); err != nil {
return err
}
count := len(items)
i.Items = make([]interface{}, count)
s := struct {
Type string `json:"type"`
}{}
for idx, raw := range items {
if err := json.Unmarshal(*raw, &s); err != nil {
return err
}
var obj interface{}
// Depending on the type, we can run json.Unmarshal again on the same byte slice
// But this time, we'll pass in the appropriate struct instead of a map
if s.Type == "user" {
obj = &User{}
} else if s.Type == "tier" {
obj = &Tier{}
} else if s.Type == "goal" {
obj = &Goal{}
} else if s.Type == "campaign" {
obj = &Campaign{}
} else if s.Type == "benefit" {
obj = &Benefit{}
} else if s.Type == "membership" {
obj = &Member{}
} else if s.Type == "member" {
obj = &Member{}
} else if s.Type == "address" {
obj = &Address{}
} else if s.Type == "patron" {
obj = &User{}
} else if s.Type == "webhook" {
obj = &Webhook{}
} else if s.Type == "deliverable" {
obj = &Deliverable{}
} else {
return fmt.Errorf("unsupported type '%s'", s.Type)
}
if err := json.Unmarshal(*raw, obj); err != nil {
return err
}
i.Items[idx] = obj
}
return nil
}