diff --git a/optional_marshaljson.go b/optional_marshaljson.go index 6233092..4d144cb 100644 --- a/optional_marshaljson.go +++ b/optional_marshaljson.go @@ -5,14 +5,20 @@ import ( "encoding/json" ) -type jsonMarshaler interface { - bool | string -} +var _ json.Marshaler = Nothing[bool]() +var _ json.Marshaler = Nothing[string]() // MarshalJSON makes it so json.Marshaler is implemented. -func (receiver Optional[jsonMarshal]) MarshalJSON() ([]byte, error) { - if !receiver.something { - return nil, fmt.Errorf("cannot marshal opt.Nothing[%T]()", receiver.value) +func (receiver Optional[T]) MarshalJSON() ([]byte, error) { + switch interface{}(receiver.value).(type) { + case bool, string: + // these are OK. + default: + return nil, fmt.Errorf("cannot marshal something of type %T into JSON because parameterized type is ‘%T’ rather than ‘bool’ or ‘string’", receiver, receiver.value) + } + + if receiver.isnothing() { + return nil, fmt.Errorf("cannot marshal opt.Nothing[%T]() into JSON", receiver.value) } return json.Marshal(receiver.value)