Skip to content

Commit 819acad

Browse files
authored
Merge pull request #398 from teou/master
use json.Marshaler then trim the last '\n' in reflect_marshaler
2 parents 695ec2b + 9764548 commit 819acad

File tree

2 files changed

+57
-2
lines changed

2 files changed

+57
-2
lines changed

api_tests/marshal_json_escape_test.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package test
2+
3+
import (
4+
"bytes"
5+
"encoding/json"
6+
"testing"
7+
8+
jsoniter "github.com/json-iterator/go"
9+
"github.com/stretchr/testify/require"
10+
)
11+
12+
var marshalConfig = jsoniter.Config{
13+
EscapeHTML: false,
14+
SortMapKeys: true,
15+
ValidateJsonRawMessage: true,
16+
}.Froze()
17+
18+
type Container struct {
19+
Bar interface{}
20+
}
21+
22+
func (c *Container) MarshalJSON() ([]byte, error) {
23+
return marshalConfig.Marshal(&c.Bar)
24+
}
25+
26+
func TestEncodeEscape(t *testing.T) {
27+
should := require.New(t)
28+
29+
container := &Container{
30+
Bar: []string{"123<ab>", "ooo"},
31+
}
32+
out, err := marshalConfig.Marshal(container)
33+
should.Nil(err)
34+
bufout := string(out)
35+
36+
var stdbuf bytes.Buffer
37+
stdenc := json.NewEncoder(&stdbuf)
38+
stdenc.SetEscapeHTML(false)
39+
err = stdenc.Encode(container)
40+
should.Nil(err)
41+
stdout := string(stdbuf.Bytes())
42+
if stdout[len(stdout)-1:] == "\n" {
43+
stdout = stdout[:len(stdout)-1]
44+
}
45+
46+
should.Equal(stdout, bufout)
47+
}

reflect_marshaler.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ package jsoniter
33
import (
44
"encoding"
55
"encoding/json"
6-
"github.com/modern-go/reflect2"
76
"unsafe"
7+
8+
"github.com/modern-go/reflect2"
89
)
910

1011
var marshalerType = reflect2.TypeOfPtr((*json.Marshaler)(nil)).Elem()
@@ -93,10 +94,17 @@ func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
9394
stream.WriteNil()
9495
return
9596
}
96-
bytes, err := json.Marshal(obj)
97+
marshaler := obj.(json.Marshaler)
98+
bytes, err := marshaler.MarshalJSON()
9799
if err != nil {
98100
stream.Error = err
99101
} else {
102+
// html escape was already done by jsoniter
103+
// but the extra '\n' should be trimed
104+
l := len(bytes)
105+
if l > 0 && bytes[l-1] == '\n' {
106+
bytes = bytes[:l-1]
107+
}
100108
stream.Write(bytes)
101109
}
102110
}

0 commit comments

Comments
 (0)