go-nul/nullable_marshaljson.go

31 lines
817 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package nul
import (
"encoding/json"
"sourcecode.social/reiver/go-erorr"
)
var _ json.Marshaler = Nothing[bool]()
var _ json.Marshaler = Nothing[string]()
// MarshalJSON makes it so json.Marshaler is implemented.
func (receiver Nullable[T]) MarshalJSON() ([]byte, error) {
switch interface{}(receiver.value).(type) {
case bool, string,json.Marshaler:
// these are OK.
default:
return nil, erorr.Errorf("nul: cannot marshal something of type %T into JSON because parameterized type is %T rather than bool, string, or json.Marshaler", receiver, receiver.value)
}
if receiver.isnothing() {
return nil, erorr.Errorf("nul: cannot marshal nul.Nothing[%T]() into JSON", receiver.value)
}
if receiver.isnull {
return json.Marshal(nil)
}
return json.Marshal(receiver.value)
}