forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
optional_object.go
43 lines (35 loc) · 1.1 KB
/
optional_object.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
package types
import "encoding/json"
// OptionalObject is for situations where we want to differentiate between an
// empty object, and the object not having been set. An example would be an
// optional command line option where we want to tell the difference between
// it being set to an empty object, and it not being specified at all.
type OptionalObject struct {
IsSet bool
Value map[string]interface{}
}
func NewOptionalObject(v map[string]interface{}) OptionalObject {
if v == nil {
// This ensures that when IsSet==true, we always have an empty map as the value which
// marshals to `{}` and not a nil map which marshals to `null`
v = make(map[string]interface{})
}
return OptionalObject{
IsSet: true,
Value: v,
}
}
func (o *OptionalObject) UnmarshalJSON(rawJSON []byte) error {
var receiver map[string]interface{}
if err := json.Unmarshal(rawJSON, &receiver); err != nil {
return err
}
*o = NewOptionalObject(receiver)
return nil
}
func (o OptionalObject) MarshalJSON() ([]byte, error) {
return json.Marshal(o.Value)
}
func (o OptionalObject) OmitJSONry() bool {
return !o.IsSet
}