فهرست منبع

Fixes #405 - Encode nil map into null

Ben Brooks 6 سال پیش
والد
کامیت
028e2ef2bd
2فایلهای تغییر یافته به همراه12 افزوده شده و 0 حذف شده
  1. 8 0
      misc_tests/jsoniter_map_test.go
  2. 4 0
      reflect_map.go

+ 8 - 0
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)
+}

+ 4 - 0
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++ {