go-nul/nullable_marshaljson.go

40 lines
1.1 KiB
Go
Raw Normal View History

2023-09-24 00:40:03 +00:00
package nul
import (
2024-08-09 03:35:44 +00:00
"encoding"
"fmt"
2024-08-07 07:37:51 +00:00
"reflect"
2023-09-27 00:48:15 +00:00
"github.com/reiver/go-erorr"
2024-08-09 03:35:44 +00:00
"github.com/reiver/go-json"
2023-09-24 00:40:03 +00:00
)
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) {
2024-08-09 03:35:44 +00:00
case json.Marshaler, encoding.TextMarshaler, bool, int, int8, int16, int32, int64, string, uint, uint8, uint16, uint32, uint64:
2023-09-24 00:40:03 +00:00
// these are OK.
default:
2024-08-09 03:35:44 +00:00
var reflectedType reflect.Type = reflect.TypeOf(receiver.value)
if nil == reflectedType {
return nil, errBadReflection
}
if reflect.Struct != reflectedType.Kind() {
return nil, erorr.Errorf("nul: cannot marshal something of type %T into JSON because parameterized type is %T is not supported", receiver, receiver.value)
2024-08-07 07:37:51 +00:00
}
2023-09-24 00:40:03 +00:00
}
if receiver.isnothing() {
2024-08-09 03:35:44 +00:00
return nil, json.ErrEmpty(fmt.Sprintf("nul: cannot marshal nul.Nothing[%T]() into JSON", receiver.value))
2023-09-24 00:40:03 +00:00
}
if receiver.isnull {
return json.Marshal(nil)
}
return json.Marshal(receiver.value)
}