mirror of
https://github.com/SagerNet/sing.git
synced 2025-04-02 03:17:37 +03:00
Fix merge objects
This commit is contained in:
parent
b55d1c78b3
commit
2238a05966
3 changed files with 50 additions and 6 deletions
|
@ -2,9 +2,11 @@ package badjson
|
|||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/json"
|
||||
cJSON "github.com/sagernet/sing/common/json/internal/contextjson"
|
||||
)
|
||||
|
||||
func MarshallObjects(objects ...any) ([]byte, error) {
|
||||
|
@ -31,16 +33,12 @@ func UnmarshallExcluded(inputContent []byte, parentObject any, object any) error
|
|||
}
|
||||
|
||||
func UnmarshallExcludedContext(ctx context.Context, inputContent []byte, parentObject any, object any) error {
|
||||
parentContent, err := newJSONObject(ctx, parentObject)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var content JSONObject
|
||||
err = content.UnmarshalJSONContext(ctx, inputContent)
|
||||
err := content.UnmarshalJSONContext(ctx, inputContent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, key := range parentContent.Keys() {
|
||||
for _, key := range cJSON.ObjectKeys(reflect.TypeOf(parentObject)) {
|
||||
content.Remove(key)
|
||||
}
|
||||
if object == nil {
|
||||
|
|
20
common/json/internal/contextjson/keys.go
Normal file
20
common/json/internal/contextjson/keys.go
Normal file
|
@ -0,0 +1,20 @@
|
|||
package json
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/sagernet/sing/common"
|
||||
)
|
||||
|
||||
func ObjectKeys(object reflect.Type) []string {
|
||||
switch object.Kind() {
|
||||
case reflect.Pointer:
|
||||
return ObjectKeys(object.Elem())
|
||||
case reflect.Struct:
|
||||
default:
|
||||
panic("invalid non-struct input")
|
||||
}
|
||||
return common.Map(cachedTypeFields(object).list, func(field field) string {
|
||||
return field.name
|
||||
})
|
||||
}
|
26
common/json/internal/contextjson/keys_test.go
Normal file
26
common/json/internal/contextjson/keys_test.go
Normal file
|
@ -0,0 +1,26 @@
|
|||
package json_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
json "github.com/sagernet/sing/common/json/internal/contextjson"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type MyObject struct {
|
||||
Hello string `json:"hello,omitempty"`
|
||||
MyWorld
|
||||
MyWorld2 string `json:"-"`
|
||||
}
|
||||
|
||||
type MyWorld struct {
|
||||
World string `json:"world,omitempty"`
|
||||
}
|
||||
|
||||
func TestObjectKeys(t *testing.T) {
|
||||
t.Parallel()
|
||||
keys := json.ObjectKeys(reflect.TypeOf(&MyObject{}))
|
||||
require.Equal(t, []string{"hello", "world"}, keys)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue