sing-box/option/json.go

78 lines
1.6 KiB
Go
Raw Normal View History

2022-07-03 01:57:04 +08:00
package option
import (
"bytes"
2022-07-03 03:42:57 +08:00
"github.com/goccy/go-json"
2022-07-03 19:43:27 +08:00
"github.com/sagernet/sing-box/common/badjson"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
2022-07-03 01:57:04 +08:00
)
2022-07-03 19:43:27 +08:00
func ToMap(v any) (*badjson.JSONObject, error) {
inputContent, err := json.Marshal(v)
2022-07-03 01:57:04 +08:00
if err != nil {
return nil, err
}
2022-07-03 19:43:27 +08:00
var content badjson.JSONObject
err = content.UnmarshalJSON(inputContent)
2022-07-03 01:57:04 +08:00
if err != nil {
return nil, err
}
2022-07-03 03:42:57 +08:00
return &content, nil
2022-07-03 01:57:04 +08:00
}
2022-07-03 19:43:27 +08:00
func MergeObjects(objects ...any) (*badjson.JSONObject, error) {
var content badjson.JSONObject
2022-07-03 01:57:04 +08:00
for _, object := range objects {
objectMap, err := ToMap(object)
if err != nil {
return nil, err
}
2022-07-03 03:42:57 +08:00
content.PutAll(objectMap)
2022-07-03 01:57:04 +08:00
}
2022-07-03 03:42:57 +08:00
return &content, nil
2022-07-03 01:57:04 +08:00
}
func MarshallObjects(objects ...any) ([]byte, error) {
objects = common.Filter(objects, func(v any) bool {
return v != nil
})
if len(objects) == 1 {
return json.Marshal(objects[0])
}
2022-07-03 01:57:04 +08:00
content, err := MergeObjects(objects...)
if err != nil {
return nil, err
}
return content.MarshalJSON()
}
func UnmarshallExcluded(inputContent []byte, parentObject any, object any) error {
parentContent, err := ToMap(parentObject)
if err != nil {
return err
}
2022-07-03 19:43:27 +08:00
var content badjson.JSONObject
err = content.UnmarshalJSON(inputContent)
if err != nil {
return err
}
2022-07-03 19:43:27 +08:00
for _, key := range parentContent.Keys() {
content.Remove(key)
}
if object == nil {
if content.IsEmpty() {
return nil
}
return E.New("unexpected key: ", content.Keys()[0])
}
inputContent, err = content.MarshalJSON()
if err != nil {
return err
}
decoder := json.NewDecoder(bytes.NewReader(inputContent))
decoder.DisallowUnknownFields()
return decoder.Decode(object)
2022-07-03 01:57:04 +08:00
}