Ver Fonte

#70 decode null to nil for map/slice

Tao Wen há 8 anos atrás
pai
commit
f771d32291
3 ficheiros alterados com 31 adições e 10 exclusões
  1. 4 0
      feature_reflect_map.go
  2. 6 0
      feature_reflect_slice.go
  3. 21 10
      jsoniter_null_test.go

+ 4 - 0
feature_reflect_map.go

@@ -23,6 +23,10 @@ func (decoder *mapDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
 	mapInterface.word = ptr
 	realInterface := (*interface{})(unsafe.Pointer(&mapInterface))
 	realVal := reflect.ValueOf(*realInterface).Elem()
+	if iter.ReadNil() {
+		realVal.Set(reflect.Zero(decoder.mapType))
+		return
+	}
 	if realVal.IsNil() {
 		realVal.Set(reflect.MakeMap(realVal.Type()))
 	}

+ 6 - 0
feature_reflect_slice.go

@@ -87,6 +87,12 @@ func (decoder *sliceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
 
 func (decoder *sliceDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) {
 	slice := (*sliceHeader)(ptr)
+	if iter.ReadNil() {
+		slice.Len = 0
+		slice.Cap = 0
+		slice.Data = nil
+		return
+	}
 	reuseSlice(slice, decoder.sliceType, 4)
 	if !iter.ReadArray() {
 		return

+ 21 - 10
jsoniter_null_test.go

@@ -32,7 +32,7 @@ func Test_encode_null(t *testing.T) {
 	should.Equal("null", str)
 }
 
-func Test_decode_null_object(t *testing.T) {
+func Test_decode_null_object_field(t *testing.T) {
 	should := require.New(t)
 	iter := ParseString(ConfigDefault, `[null,"a"]`)
 	iter.ReadArray()
@@ -51,16 +51,27 @@ func Test_decode_null_object(t *testing.T) {
 	should.Len(objs, 1)
 }
 
-func Test_decode_null_array(t *testing.T) {
+func Test_decode_null_array_element(t *testing.T) {
+	should := require.New(t)
 	iter := ParseString(ConfigDefault, `[null,"a"]`)
-	iter.ReadArray()
-	if iter.ReadArray() != false {
-		t.FailNow()
-	}
-	iter.ReadArray()
-	if iter.ReadString() != "a" {
-		t.FailNow()
-	}
+	should.True(iter.ReadArray())
+	should.True(iter.ReadNil())
+	should.True(iter.ReadArray())
+	should.Equal("a", iter.ReadString())
+}
+
+func Test_decode_null_array(t *testing.T) {
+	should := require.New(t)
+	arr := []string{}
+	should.Nil(UnmarshalFromString("null", &arr))
+	should.Nil(arr)
+}
+
+func Test_decode_null_map(t *testing.T) {
+	should := require.New(t)
+	arr := map[string]string{}
+	should.Nil(UnmarshalFromString("null", &arr))
+	should.Nil(arr)
 }
 
 func Test_decode_null_string(t *testing.T) {