Skip to content

Commit 0828e55

Browse files
committed
#164 support interface{} with ptr
1 parent 8c7fc75 commit 0828e55

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

feature_reflect_native.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"encoding/base64"
66
"encoding/json"
77
"unsafe"
8+
"reflect"
89
)
910

1011
type stringCodec struct {
@@ -349,7 +350,12 @@ type emptyInterfaceCodec struct {
349350
}
350351

351352
func (codec *emptyInterfaceCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
352-
*((*interface{})(ptr)) = iter.Read()
353+
existing := *((*interface{})(ptr))
354+
if existing != nil && reflect.TypeOf(existing).Kind() == reflect.Ptr {
355+
iter.ReadVal(existing)
356+
} else {
357+
*((*interface{})(ptr)) = iter.Read()
358+
}
353359
}
354360

355361
func (codec *emptyInterfaceCodec) Encode(ptr unsafe.Pointer, stream *Stream) {

jsoniter_interface_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"github.com/stretchr/testify/require"
66
"testing"
77
"unsafe"
8+
"fmt"
89
)
910

1011
func Test_write_array_of_interface(t *testing.T) {
@@ -297,3 +298,18 @@ func Test_array_with_nothing(t *testing.T) {
297298
should.Nil(err)
298299
should.Equal(`[null,null]`, output)
299300
}
301+
302+
func Test_unmarshal_ptr_to_interface(t *testing.T) {
303+
type TestData struct {
304+
Name string `json:"name"`
305+
}
306+
should := require.New(t)
307+
var obj interface{} = &TestData{}
308+
err := json.Unmarshal([]byte(`{"name":"value"}`), &obj)
309+
should.Nil(err)
310+
should.Equal("&{value}", fmt.Sprintf("%v", obj))
311+
obj = interface{}(&TestData{})
312+
err = Unmarshal([]byte(`{"name":"value"}`), &obj)
313+
should.Nil(err)
314+
should.Equal("&{value}", fmt.Sprintf("%v", obj))
315+
}

0 commit comments

Comments
 (0)