badjson: Fix Listable

This commit is contained in:
世界 2024-11-16 12:16:33 +08:00
parent e52e04f721
commit fdca9b3f8e
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
2 changed files with 10 additions and 10 deletions

View file

@ -11,7 +11,7 @@ import (
) )
func Omitempty[T any](ctx context.Context, value T) (T, error) { func Omitempty[T any](ctx context.Context, value T) (T, error) {
objectContent, err := json.Marshal(value) objectContent, err := json.MarshalContext(ctx, value)
if err != nil { if err != nil {
return common.DefaultValue[T](), E.Cause(err, "marshal object") return common.DefaultValue[T](), E.Cause(err, "marshal object")
} }

View file

@ -9,24 +9,24 @@ import (
type Listable[T any] []T type Listable[T any] []T
func (l Listable[T]) MarshalJSON() ([]byte, error) { func (l Listable[T]) MarshalJSONContext(ctx context.Context) ([]byte, error) {
arrayList := []T(l) arrayList := []T(l)
if len(arrayList) == 1 { if len(arrayList) == 1 {
return json.Marshal(arrayList[0]) return json.Marshal(arrayList[0])
} }
return json.Marshal(arrayList) return json.MarshalContext(ctx, arrayList)
} }
func (l *Listable[T]) UnmarshalJSONContext(ctx context.Context, content []byte) error { func (l *Listable[T]) UnmarshalJSONContext(ctx context.Context, content []byte) error {
err := json.UnmarshalContextDisallowUnknownFields(ctx, content, (*[]T)(l)) var singleItem T
err := json.UnmarshalContextDisallowUnknownFields(ctx, content, &singleItem)
if err == nil { if err == nil {
*l = []T{singleItem}
return nil return nil
} }
var singleItem T newErr := json.UnmarshalContextDisallowUnknownFields(ctx, content, (*[]T)(l))
newError := json.UnmarshalContextDisallowUnknownFields(ctx, content, &singleItem) if newErr == nil {
if newError != nil { return nil
return E.Errors(err, newError)
} }
*l = []T{singleItem} return E.Errors(err, newErr)
return nil
} }