Refactor json

This commit is contained in:
世界 2022-07-03 19:43:27 +08:00
parent dd56b2584b
commit 28b865acf0
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
8 changed files with 179 additions and 188 deletions

46
common/badjson/array.go Normal file
View file

@ -0,0 +1,46 @@
package badjson
import (
"bytes"
"github.com/goccy/go-json"
E "github.com/sagernet/sing/common/exceptions"
)
type JSONArray[T any] []T
func (a JSONArray[T]) MarshalJSON() ([]byte, error) {
return json.Marshal([]T(a))
}
func (a *JSONArray[T]) UnmarshalJSON(content []byte) error {
decoder := json.NewDecoder(bytes.NewReader(content))
arrayStart, err := decoder.Token()
if err != nil {
return err
} else if arrayStart != json.Delim('[') {
return E.New("excepted array start, but got ", arrayStart)
}
err = a.decodeJSON(decoder)
if err != nil {
return err
}
arrayEnd, err := decoder.Token()
if err != nil {
return err
} else if arrayEnd != json.Delim(']') {
return E.New("excepted array end, but got ", arrayEnd)
}
return nil
}
func (a *JSONArray[T]) decodeJSON(decoder *json.Decoder) error {
for decoder.More() {
var item T
err := decoder.Decode(&item)
if err != nil {
return err
}
}
return nil
}