From 028e2ef2bd976bae587f7323f47bf34c5559a4b9 Mon Sep 17 00:00:00 2001 From: Ben Brooks Date: Thu, 19 Sep 2019 13:11:30 +0100 Subject: [PATCH] Fixes #405 - Encode nil map into null --- misc_tests/jsoniter_map_test.go | 8 ++++++++ reflect_map.go | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/misc_tests/jsoniter_map_test.go b/misc_tests/jsoniter_map_test.go index b0dde94..b73de69 100644 --- a/misc_tests/jsoniter_map_test.go +++ b/misc_tests/jsoniter_map_test.go @@ -42,3 +42,11 @@ func Test_map_eface_of_eface(t *testing.T) { should.NoError(err) should.Equal(`{"1":2,"3":"4"}`, output) } + +func Test_encode_nil_map(t *testing.T) { + should := require.New(t) + var nilMap map[string]string + output, err := jsoniter.MarshalToString(nilMap) + should.NoError(err) + should.Equal(`null`, output) +} diff --git a/reflect_map.go b/reflect_map.go index 547b442..08e9a39 100644 --- a/reflect_map.go +++ b/reflect_map.go @@ -249,6 +249,10 @@ type mapEncoder struct { } func (encoder *mapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *(*unsafe.Pointer)(ptr) == nil { + stream.WriteNil() + return + } stream.WriteObjectStart() iter := encoder.mapType.UnsafeIterate(ptr) for i := 0; iter.HasNext(); i++ {