From e6c24947ee7e57331bb4cf0de05fc7b7a5e180ee Mon Sep 17 00:00:00 2001 From: Tao Wen Date: Thu, 29 Jun 2017 18:58:40 +0800 Subject: [PATCH] array is just like struct, one element case special for interface{ --- feature_reflect_array.go | 11 ++++++++++- jsoniter_interface_test.go | 11 ++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/feature_reflect_array.go b/feature_reflect_array.go index 29959b1..809a332 100644 --- a/feature_reflect_array.go +++ b/feature_reflect_array.go @@ -56,7 +56,16 @@ func (encoder *arrayEncoder) EncodeInterface(val interface{}, stream *Stream) { stream.WriteArrayEnd() return } - WriteToStream(val, stream, encoder) + elemType := encoder.arrayType.Elem() + if encoder.arrayType.Len() == 1 && (elemType.Kind() == reflect.Ptr ||elemType.Kind() == reflect.Map) { + ptr := uintptr(e.word) + e.word = unsafe.Pointer(&ptr) + } + if reflect.TypeOf(val).Kind() == reflect.Ptr { + encoder.Encode(unsafe.Pointer(&e.word), stream) + } else { + encoder.Encode(e.word, stream) + } } func (encoder *arrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { diff --git a/jsoniter_interface_test.go b/jsoniter_interface_test.go index 9a53f6a..e429c31 100644 --- a/jsoniter_interface_test.go +++ b/jsoniter_interface_test.go @@ -233,7 +233,7 @@ func Test_struct_with_not_nil_embedded(t *testing.T) { should.Equal("1", obj.Field0) } -func Test_array_with_one_nil(t *testing.T) { +func Test_array_with_one_nil_ptr(t *testing.T) { obj := [1]*float64{nil} should := require.New(t) output, err := MarshalToString(obj) @@ -241,6 +241,15 @@ func Test_array_with_one_nil(t *testing.T) { should.Equal(`[null]`, output) } +func Test_array_with_one_not_nil_ptr(t *testing.T) { + two := float64(2) + obj := [1]*float64{&two} + should := require.New(t) + output, err := MarshalToString(obj) + should.Nil(err) + should.Equal(`[2]`, output) +} + func Test_embedded_array_with_one_nil(t *testing.T) { type TestObject struct { Field1 int