Ordered json output & Disallow unknown fields

This commit is contained in:
世界 2022-07-03 11:28:15 +08:00
parent 85a695caa1
commit ef5cfd59d4
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
16 changed files with 243 additions and 26 deletions

View file

@ -1,18 +1,19 @@
package option
import (
"encoding/json"
"bytes"
"github.com/sagernet/sing/common/x/linkedhashmap"
"github.com/goccy/go-json"
"github.com/sagernet/sing-box/common/linkedhashmap"
)
func ToMap(v any) (*linkedhashmap.Map[string, any], error) {
bytes, err := json.Marshal(v)
inputContent, err := json.Marshal(v)
if err != nil {
return nil, err
}
var content linkedhashmap.Map[string, any]
err = json.Unmarshal(bytes, &content)
err = content.UnmarshalJSON(inputContent)
if err != nil {
return nil, err
}
@ -36,5 +37,25 @@ func MarshallObjects(objects ...any) ([]byte, error) {
if err != nil {
return nil, err
}
return json.Marshal(content)
return content.MarshalJSON()
}
func UnmarshallExcluded(inputContent []byte, parentObject any, object any) error {
parentContent, err := ToMap(parentObject)
if err != nil {
return err
}
var content linkedhashmap.Map[string, any]
err = content.UnmarshalJSON(inputContent)
if err != nil {
return err
}
content.RemoveAll(parentContent.Keys())
inputContent, err = content.MarshalJSON()
if err != nil {
return err
}
decoder := json.NewDecoder(bytes.NewReader(inputContent))
decoder.DisallowUnknownFields()
return decoder.Decode(object)
}