Skip to content

fix: compatibility in umarshaling "null" into json.RawMessage #700

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions misc_tests/jsoniter_raw_message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package misc_tests

import (
"encoding/json"
"github.com/json-iterator/go"
"github.com/stretchr/testify/require"
"strings"
"testing"

jsoniter "github.com/json-iterator/go"
"github.com/stretchr/testify/require"
)

func Test_jsoniter_RawMessage(t *testing.T) {
Expand Down Expand Up @@ -58,7 +59,26 @@ func Test_marshal_nil_json_raw_message(t *testing.T) {
a.Nil2 = []byte(`Any`)
should.Nil(jsoniter.Unmarshal(aout, &a))
should.Nil(a.Nil1)
should.Nil(a.Nil2)
should.Equal(a.Nil2, json.RawMessage("null"))
}

func Test_unmarshal_nil_json_raw_message_compatibility(t *testing.T) {
type A struct {
Nil1 json.RawMessage `json:"raw1"`
Nil2 json.RawMessage `json:"raw2"`
}

a1 := A{}
a2 := A{}
should := require.New(t)
data := []byte(`{"raw1":null}`)
err1 := json.Unmarshal(data, &a1)
err2 := jsoniter.Unmarshal(data, &a2)
should.Equal(a1.Nil1, a2.Nil1)
should.Nil(a1.Nil2)
should.Nil(a2.Nil2)
should.Nil(err1)
should.Nil(err2)
}

func Test_raw_message_memory_not_copied_issue(t *testing.T) {
Expand Down
9 changes: 3 additions & 6 deletions reflect_json_raw_message.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ package jsoniter

import (
"encoding/json"
"github.com/modern-go/reflect2"
"unsafe"

"github.com/modern-go/reflect2"
)

var jsonRawMessageType = reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()
Expand Down Expand Up @@ -33,11 +34,7 @@ type jsonRawMessageCodec struct {
}

func (codec *jsonRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
if iter.ReadNil() {
*((*json.RawMessage)(ptr)) = nil
} else {
*((*json.RawMessage)(ptr)) = iter.SkipAndReturnBytes()
}
*((*json.RawMessage)(ptr)) = iter.SkipAndReturnBytes()
}

func (codec *jsonRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
Expand Down