Skip to content

Commit

Permalink
Merge pull request #337 from denverdino/fix-encode-with-MarshalJSON
Browse files Browse the repository at this point in the history
Fix the incompatible encoding #336
  • Loading branch information
taowen authored Jan 14, 2019
2 parents d05f387 + e4aa2ec commit 2d42ff7
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
36 changes: 36 additions & 0 deletions api_tests/marshal_json_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
3 changes: 1 addition & 2 deletions reflect_marshaler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 2d42ff7

Please sign in to comment.