Skip to content

Commit 82ef1cf

Browse files
committed
Merge branch 'master' of github.com:bytedance/go-tagexpr
Change-Id: Ib2452c4f10ab783f00311268b14f6180967b27f6
2 parents 33295b6 + 987dbec commit 82ef1cf

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed

binding/gjson/gjson.go

+11-2
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,10 @@ import (
3838
"github.com/bytedance/go-tagexpr/v2/binding/gjson/internal/rt"
3939
)
4040

41-
var programCache = caching.CreateProgramCache()
41+
var (
42+
programCache = caching.CreateProgramCache()
43+
unmarshalerInterface = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()
44+
)
4245

4346
func init() {
4447
gjson.DisableModifiers = true
@@ -97,7 +100,13 @@ func assign(jsval gjson.Result, goval reflect.Value) (err error) {
97100
goval.Set(reflect.ValueOf(data))
98101
} else {
99102
if !jsval.IsArray() {
100-
return nil
103+
// canAddr: true, implement unmarshaler : true -> continue
104+
// canAddr: true, implement unmarshaler : false -> return
105+
// canAddr: false, implement unmarshaler : true -> return
106+
// canAddr: false, implement unmarshaler : false -> return
107+
if !goval.CanAddr() || !goval.Addr().Type().Implements(unmarshalerInterface) {
108+
return nil
109+
}
101110
}
102111
jsvals := jsval.Array()
103112
slice := reflect.MakeSlice(t, len(jsvals), len(jsvals))

binding/gjson/gjson_test.go

+40
Original file line numberDiff line numberDiff line change
@@ -236,3 +236,43 @@ func getFiledInfoWithMap(t reflect.Type) map[string][]int {
236236
}
237237
return sf
238238
}
239+
240+
241+
// MarshalJSON to output non base64 encoded []byte
242+
func (j ByteSlice) MarshalJSON() ([]byte, error) {
243+
if len(j) == 0 {
244+
return []byte("null"), nil
245+
}
246+
247+
return json.RawMessage(j).MarshalJSON()
248+
}
249+
250+
// UnmarshalJSON to deserialize []byte
251+
func (j *ByteSlice) UnmarshalJSON(b []byte) error {
252+
result := json.RawMessage{}
253+
err := result.UnmarshalJSON(b)
254+
*j = ByteSlice(result)
255+
return err
256+
}
257+
258+
type ByteSlice []byte
259+
260+
func TestCustomizedGjsonUnmarshal(t *testing.T) {
261+
str := `{"h1":{"h2":1}}`
262+
type F struct {
263+
H ByteSlice `json:"h1"`
264+
}
265+
266+
obj := F{}
267+
err := Unmarshal([]byte(str), &obj)
268+
269+
assert.NoError(t, err)
270+
assert.Equal(t, "{\"h2\":1}", string(obj.H))
271+
272+
obj2 := F{}
273+
err = json.Unmarshal([]byte(str), &obj2)
274+
assert.NoError(t, err)
275+
assert.Equal(t, "{\"h2\":1}", string(obj2.H))
276+
277+
assert.Equal(t, obj.H, obj2.H)
278+
}

0 commit comments

Comments
 (0)