go-opt/optional_unmarshaljson.go

34 lines
780 B
Go
Raw Normal View History

2023-09-23 21:27:34 +00:00
package opt
import (
"encoding/json"
2023-09-27 00:43:16 +00:00
"sourcecode.social/reiver/go-erorr"
2023-09-23 21:27:34 +00:00
)
var _ json.Unmarshaler = new(Optional[bool])
var _ json.Unmarshaler = new(Optional[string])
// UnmarshalJSON makes it so json.Unmarshaler is implemented.
func (receiver *Optional[T]) UnmarshalJSON(data []byte) error {
2023-09-24 22:04:29 +00:00
switch interface{}(&receiver.value).(type) {
case *bool, *string, json.Unmarshaler:
2023-09-23 21:27:34 +00:00
// these are OK.
default:
2023-09-27 00:43:16 +00:00
return erorr.Errorf("opt: cannot unmarshal into something of type %T from JSON because pointer to parameterized type is %T rather than *bool, *string, or json.Unmarshaler", receiver, &receiver.value)
2023-09-23 21:27:34 +00:00
}
{
var dst T
err := json.Unmarshal(data, &dst)
if nil != err {
return err
}
*receiver = Something(dst)
}
return nil
}