Quellcode durchsuchen

Merge pull request #169 from toffaletti/fix-nil-interface

Fix handling of nil empty interface
Tao Wen vor 8 Jahren
Ursprung
Commit
eef35e549b
2 geänderte Dateien mit 21 neuen und 1 gelöschten Zeilen
  1. 2 1
      feature_reflect_native.go
  2. 19 0
      jsoniter_interface_test.go

+ 2 - 1
feature_reflect_native.go

@@ -373,7 +373,8 @@ func (codec *emptyInterfaceCodec) EncodeInterface(val interface{}, stream *Strea
 }
 
 func (codec *emptyInterfaceCodec) IsEmpty(ptr unsafe.Pointer) bool {
-	return ptr == nil
+	emptyInterface := (*emptyInterface)(ptr)
+	return emptyInterface.typ == nil
 }
 
 type nonEmptyInterfaceCodec struct {

+ 19 - 0
jsoniter_interface_test.go

@@ -351,3 +351,22 @@ func Test_nil_out_null_interface(t *testing.T) {
 	should.Equal(nil, err)
 	should.Equal(nil, obj2.Field)
 }
+
+func Test_omitempty_nil_interface(t *testing.T) {
+	type TestData struct {
+		Field interface{} `json:"field,omitempty"`
+	}
+	should := require.New(t)
+
+	obj := TestData{
+		Field: nil,
+	}
+
+	js, err := json.Marshal(obj)
+	should.Equal(nil, err)
+	should.Equal("{}", string(js))
+
+	str, err := MarshalToString(obj)
+	should.Equal(nil, err)
+	should.Equal(string(js), str)
+}