-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoding_json.go
99 lines (82 loc) · 2.23 KB
/
encoding_json.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package effects
import (
"encoding/json"
"reflect"
)
// Effect envelopes
type _effectEnvelope EffectEnvelope
type effectMarshalFormat struct {
_effectEnvelope // using a type alias prevents json.Marshal from recursing
Type string
}
type effectUnmarshalFormat struct {
effectMarshalFormat
Effect *json.RawMessage // this can only be unpacked once the Type is known
Params *json.RawMessage // alias for Effect
}
func (e *EffectEnvelope) MarshalJSON() ([]byte, error) {
return json.Marshal(effectMarshalFormat{
Type: reflect.TypeOf(e.Effect).Elem().Name(),
_effectEnvelope: _effectEnvelope(*e),
})
}
func (e *EffectEnvelope) UnmarshalJSON(b []byte) error {
var tmp effectUnmarshalFormat
if err := json.Unmarshal(b, &tmp); err == nil {
e.Effect = NewByName(tmp.Type)
e.Controls = tmp.Controls
e.Disabled = tmp.Disabled
if tmp.Effect != nil {
return json.Unmarshal(*tmp.Effect, &e.Effect)
} else if tmp.Params != nil {
return json.Unmarshal(*tmp.Params, &e.Effect)
} else {
return nil
}
} else {
return err
}
}
// Control envelopes
type _controlEnvelope ControlEnvelope
type controlMarshalFormat struct {
_controlEnvelope // using a type alias prevents json.Marshal from recursing
Type string
}
type controlUnmarshalFormat struct {
controlMarshalFormat
Control *json.RawMessage // this can only be unpacked once the Type is known
}
func (e *ControlEnvelope) MarshalJSON() ([]byte, error) {
return json.Marshal(controlMarshalFormat{
_controlEnvelope: _controlEnvelope(*e),
Type: reflect.TypeOf(e.Control).Elem().Name(),
})
}
func (e *ControlEnvelope) UnmarshalJSON(b []byte) error {
var tmp controlUnmarshalFormat
if err := json.Unmarshal(b, &tmp); err == nil {
e.Control = ControlByName(tmp.Type)
e.Controls = tmp.Controls
e.Disabled = tmp.Disabled
if tmp.Control != nil {
return json.Unmarshal(*tmp.Control, &e.Control)
} else {
return nil
}
} else {
return err
}
}
// Helper functions
func MarshalJSON(effects EffectSet) ([]byte, error) {
return json.Marshal(effects)
}
func UnmarshalJSON(b []byte) (EffectSet, error) {
var effects EffectSet
if err := json.Unmarshal(b, &effects); err == nil {
return effects, nil
} else {
return nil, err
}
}