Skip to content

Commit e45886b

Browse files
committed
Fix merge objects
1 parent 5f99dc8 commit e45886b

File tree

3 files changed

+50
-6
lines changed

3 files changed

+50
-6
lines changed

common/json/badjson/merge_objects.go

+4-6
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ package badjson
22

33
import (
44
"context"
5+
"reflect"
56

67
E "github.com/sagernet/sing/common/exceptions"
78
"github.com/sagernet/sing/common/json"
9+
cJSON "github.com/sagernet/sing/common/json/internal/contextjson"
810
)
911

1012
func MarshallObjects(objects ...any) ([]byte, error) {
@@ -31,16 +33,12 @@ func UnmarshallExcluded(inputContent []byte, parentObject any, object any) error
3133
}
3234

3335
func UnmarshallExcludedContext(ctx context.Context, inputContent []byte, parentObject any, object any) error {
34-
parentContent, err := newJSONObject(ctx, parentObject)
35-
if err != nil {
36-
return err
37-
}
3836
var content JSONObject
39-
err = content.UnmarshalJSONContext(ctx, inputContent)
37+
err := content.UnmarshalJSONContext(ctx, inputContent)
4038
if err != nil {
4139
return err
4240
}
43-
for _, key := range parentContent.Keys() {
41+
for _, key := range cJSON.ObjectKeys(reflect.TypeOf(parentObject)) {
4442
content.Remove(key)
4543
}
4644
if object == nil {
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package json
2+
3+
import (
4+
"reflect"
5+
6+
"github.com/sagernet/sing/common"
7+
)
8+
9+
func ObjectKeys(object reflect.Type) []string {
10+
switch object.Kind() {
11+
case reflect.Pointer:
12+
return ObjectKeys(object.Elem())
13+
case reflect.Struct:
14+
default:
15+
panic("invalid non-struct input")
16+
}
17+
return common.Map(cachedTypeFields(object).list, func(field field) string {
18+
return field.name
19+
})
20+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package json_test
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
7+
json "github.com/sagernet/sing/common/json/internal/contextjson"
8+
9+
"github.com/stretchr/testify/require"
10+
)
11+
12+
type MyObject struct {
13+
Hello string `json:"hello,omitempty"`
14+
MyWorld
15+
MyWorld2 string `json:"-"`
16+
}
17+
18+
type MyWorld struct {
19+
World string `json:"world,omitempty"`
20+
}
21+
22+
func TestObjectKeys(t *testing.T) {
23+
t.Parallel()
24+
keys := json.ObjectKeys(reflect.TypeOf(&MyObject{}))
25+
require.Equal(t, []string{"hello", "world"}, keys)
26+
}

0 commit comments

Comments
 (0)