-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
38 lines (31 loc) · 862 Bytes
/
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
package option
import "encoding/json"
// MarshalJSON implements the [json.Marshaler] interface.
//
// - [Some] variants will be marshaled as their underlying value.
// - [None] variants will be marshaled as "null".
func (o Option[T]) MarshalJSON() ([]byte, error) {
if value, ok := o.Value(); ok {
return json.Marshal(value)
}
return []byte("null"), nil
}
// UnmarshalJSON implements the [json.Unmarshaler] interface.
//
// - Values will be unmarshaled as [Some] variants.
// - "null"s will be unmarshaled as [None] variants.
func (o *Option[T]) UnmarshalJSON(data []byte) error {
*o = None[T]()
if string(data) != "null" {
var value T
if err := json.Unmarshal(data, &value); err != nil {
return err
}
*o = Some(value)
}
return nil
}
var (
_ json.Unmarshaler = new(Option[struct{}])
_ json.Marshaler = Option[struct{}]{}
)