Skip to content

Commit 2d42ff7

Browse files
authored
Merge pull request #337 from denverdino/fix-encode-with-MarshalJSON
Fix the incompatible encoding #336
2 parents d05f387 + e4aa2ec commit 2d42ff7

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

api_tests/marshal_json_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package test
2+
3+
import (
4+
"bytes"
5+
"encoding/json"
6+
"github.com/json-iterator/go"
7+
"testing"
8+
"github.com/stretchr/testify/require"
9+
)
10+
11+
12+
type Foo struct {
13+
Bar interface{}
14+
}
15+
16+
func (f Foo) MarshalJSON() ([]byte, error) {
17+
var buf bytes.Buffer
18+
err := json.NewEncoder(&buf).Encode(f.Bar)
19+
return buf.Bytes(), err
20+
}
21+
22+
23+
// Standard Encoder has trailing newline.
24+
func TestEncodeMarshalJSON(t *testing.T) {
25+
26+
foo := Foo {
27+
Bar: 123,
28+
}
29+
should := require.New(t)
30+
var buf, stdbuf bytes.Buffer
31+
enc := jsoniter.ConfigCompatibleWithStandardLibrary.NewEncoder(&buf)
32+
enc.Encode(foo)
33+
stdenc := json.NewEncoder(&stdbuf)
34+
stdenc.Encode(foo)
35+
should.Equal(stdbuf.Bytes(), buf.Bytes())
36+
}

reflect_marshaler.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,7 @@ func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
9393
stream.WriteNil()
9494
return
9595
}
96-
marshaler := obj.(json.Marshaler)
97-
bytes, err := marshaler.MarshalJSON()
96+
bytes, err := json.Marshal(obj)
9897
if err != nil {
9998
stream.Error = err
10099
} else {

0 commit comments

Comments
 (0)