Compare commits

...

1 commit

Author SHA1 Message Date
世界
1ccfbdb861
badjson: Fix Listable 2024-11-16 12:16:33 +08:00
2 changed files with 11 additions and 11 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 {
*l = []T{singleItem}
return nil
}
newErr := json.UnmarshalContextDisallowUnknownFields(ctx, content, (*[]T)(l))
if err == nil { if err == nil {
return nil return nil
} }
var singleItem T return E.Errors(err, newErr)
newError := json.UnmarshalContextDisallowUnknownFields(ctx, content, &singleItem)
if newError != nil {
return E.Errors(err, newError)
}
*l = []T{singleItem}
return nil
} }