Skip to content

Commit

Permalink
badjson: Fix Listable
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Nov 16, 2024
1 parent e52e04f commit fdca9b3
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
2 changes: 1 addition & 1 deletion common/json/badjson/merge.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
)

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 {
return common.DefaultValue[T](), E.Cause(err, "marshal object")
}
Expand Down
18 changes: 9 additions & 9 deletions common/json/badoption/listable.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,24 @@ import (

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)
if len(arrayList) == 1 {
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 {
err := json.UnmarshalContextDisallowUnknownFields(ctx, content, (*[]T)(l))
var singleItem T
err := json.UnmarshalContextDisallowUnknownFields(ctx, content, &singleItem)
if err == nil {
*l = []T{singleItem}
return nil
}
var singleItem T
newError := json.UnmarshalContextDisallowUnknownFields(ctx, content, &singleItem)
if newError != nil {
return E.Errors(err, newError)
newErr := json.UnmarshalContextDisallowUnknownFields(ctx, content, (*[]T)(l))
if newErr == nil {
return nil
}
*l = []T{singleItem}
return nil
return E.Errors(err, newErr)
}

0 comments on commit fdca9b3

Please sign in to comment.