2022-07-02 14:55:10 +00:00
|
|
|
package option
|
|
|
|
|
|
|
|
import "encoding/json"
|
|
|
|
|
2022-07-02 17:57:04 +00:00
|
|
|
type Listable[T comparable] []T
|
2022-07-02 14:55:10 +00:00
|
|
|
|
2022-07-02 19:42:57 +00:00
|
|
|
func (l Listable[T]) MarshalJSON() ([]byte, error) {
|
|
|
|
arrayList := []T(l)
|
2022-07-02 14:55:10 +00:00
|
|
|
if len(arrayList) == 1 {
|
|
|
|
return json.Marshal(arrayList[0])
|
|
|
|
}
|
|
|
|
return json.Marshal(arrayList)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *Listable[T]) UnmarshalJSON(bytes []byte) error {
|
|
|
|
err := json.Unmarshal(bytes, (*[]T)(l))
|
|
|
|
if err == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
var singleItem T
|
|
|
|
err = json.Unmarshal(bytes, &singleItem)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
*l = []T{singleItem}
|
|
|
|
return nil
|
|
|
|
}
|