From e4aa2ec063d8525596a5c468fd0678813120887d Mon Sep 17 00:00:00 2001 From: Li Yi Date: Thu, 3 Jan 2019 18:19:22 +0800 Subject: [PATCH] Fix the incompatible encoding --- api_tests/marshal_json_test.go | 36 ++++++++++++++++++++++++++++++++++ reflect_marshaler.go | 3 +-- 2 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 api_tests/marshal_json_test.go diff --git a/api_tests/marshal_json_test.go b/api_tests/marshal_json_test.go new file mode 100644 index 0000000..635a24e --- /dev/null +++ b/api_tests/marshal_json_test.go @@ -0,0 +1,36 @@ +package test + +import ( + "bytes" + "encoding/json" + "github.com/json-iterator/go" + "testing" + "github.com/stretchr/testify/require" +) + + +type Foo struct { + Bar interface{} +} + +func (f Foo) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + err := json.NewEncoder(&buf).Encode(f.Bar) + return buf.Bytes(), err +} + + +// Standard Encoder has trailing newline. +func TestEncodeMarshalJSON(t *testing.T) { + + foo := Foo { + Bar: 123, + } + should := require.New(t) + var buf, stdbuf bytes.Buffer + enc := jsoniter.ConfigCompatibleWithStandardLibrary.NewEncoder(&buf) + enc.Encode(foo) + stdenc := json.NewEncoder(&stdbuf) + stdenc.Encode(foo) + should.Equal(stdbuf.Bytes(), buf.Bytes()) +} diff --git a/reflect_marshaler.go b/reflect_marshaler.go index 58ac959..fea5071 100644 --- a/reflect_marshaler.go +++ b/reflect_marshaler.go @@ -93,8 +93,7 @@ func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { stream.WriteNil() return } - marshaler := obj.(json.Marshaler) - bytes, err := marshaler.MarshalJSON() + bytes, err := json.Marshal(obj) if err != nil { stream.Error = err } else {