github.com/inazumav/sing-box@v0.0.0-20230926072359-ab51429a14f1/common/badjson/array.go (about) 1 package badjson 2 3 import ( 4 "bytes" 5 6 "github.com/inazumav/sing-box/common/json" 7 E "github.com/sagernet/sing/common/exceptions" 8 ) 9 10 type JSONArray []any 11 12 func (a JSONArray) MarshalJSON() ([]byte, error) { 13 return json.Marshal([]any(a)) 14 } 15 16 func (a *JSONArray) UnmarshalJSON(content []byte) error { 17 decoder := json.NewDecoder(bytes.NewReader(content)) 18 arrayStart, err := decoder.Token() 19 if err != nil { 20 return err 21 } else if arrayStart != json.Delim('[') { 22 return E.New("excepted array start, but got ", arrayStart) 23 } 24 err = a.decodeJSON(decoder) 25 if err != nil { 26 return err 27 } 28 arrayEnd, err := decoder.Token() 29 if err != nil { 30 return err 31 } else if arrayEnd != json.Delim(']') { 32 return E.New("excepted array end, but got ", arrayEnd) 33 } 34 return nil 35 } 36 37 func (a *JSONArray) decodeJSON(decoder *json.Decoder) error { 38 for decoder.More() { 39 item, err := decodeJSON(decoder) 40 if err != nil { 41 return err 42 } 43 *a = append(*a, item) 44 } 45 return nil 46 }