go-nul/nullable_unmarshaljson.go

46 lines
1004 B
Go
Raw Normal View History

2023-09-24 08:48:58 +00:00
package nul
import (
"encoding/json"
2023-09-27 00:48:15 +00:00
"sourcecode.social/reiver/go-erorr"
2023-09-24 08:48:58 +00:00
)
2023-11-06 17:24:20 +00:00
const errNilReceiver = erorr.Error("nul: nil receiver")
2023-09-24 08:48:58 +00:00
var _ json.Unmarshaler = new(Nullable[bool])
var _ json.Unmarshaler = new(Nullable[string])
// UnmarshalJSON makes it so json.Unmarshaler is implemented.
func (receiver *Nullable[T]) UnmarshalJSON(data []byte) error {
2023-11-06 17:24:20 +00:00
if nil == receiver {
return errNilReceiver
}
2023-09-24 08:48:58 +00:00
switch interface{}(receiver.value).(type) {
2023-09-27 00:48:15 +00:00
case bool, string,json.Unmarshaler:
2023-09-24 08:48:58 +00:00
// these are OK.
default:
2023-09-27 00:48:15 +00:00
return erorr.Errorf("nul: cannot unmarshal into something of type %T from JSON because parameterized type is %T rather than bool, string, or json.Unmarshaler", receiver, receiver.value)
2023-09-24 08:48:58 +00:00
}
if 4 == len(data) && 'n' == data[0] && 'u' == data[1] && 'l' == data[2] && 'l' == data[3] {
*receiver = Null[T]()
return nil
}
{
var dst T
err := json.Unmarshal(data, &dst)
if nil != err {
return err
}
*receiver = Something(dst)
}
return nil
}