Fix infinite loop in JsonSerializer.WriteValue (dotnet/corefx#38892)
authorBrennan <brecon@microsoft.com>
Tue, 25 Jun 2019 20:32:00 +0000 (13:32 -0700)
committerAhson Khan <ahkha@microsoft.com>
Tue, 25 Jun 2019 20:32:00 +0000 (13:32 -0700)
Commit migrated from https://github.com/dotnet/corefx/commit/98937e7f1d4882395722dedadcf57df23d0ea13f

src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.cs
src/libraries/System.Text.Json/tests/Serialization/WriteValueTests.cs [new file with mode: 0644]
src/libraries/System.Text.Json/tests/System.Text.Json.Tests.csproj

index 2f5935e..e6c14d5 100644 (file)
@@ -19,6 +19,7 @@ namespace System.Text.Json
             ref WriteStack state)
         {
             bool finishedSerializing;
+            int currentDepth = writer.CurrentDepth;
 
             try
             {
@@ -52,7 +53,7 @@ namespace System.Text.Json
 
                     if (finishedSerializing)
                     {
-                        if (writer.CurrentDepth == 0)
+                        if (writer.CurrentDepth == 0 || writer.CurrentDepth == currentDepth)
                         {
                             break;
                         }
diff --git a/src/libraries/System.Text.Json/tests/Serialization/WriteValueTests.cs b/src/libraries/System.Text.Json/tests/Serialization/WriteValueTests.cs
new file mode 100644 (file)
index 0000000..58c417d
--- /dev/null
@@ -0,0 +1,29 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.IO;
+using Xunit;
+
+namespace System.Text.Json.Serialization.Tests
+{
+    public static partial class WriteValueTests
+    {
+        [Fact]
+        public static void CanWriteValueToJsonArray()
+        {
+            using MemoryStream memoryStream = new MemoryStream();
+            using Utf8JsonWriter writer = new Utf8JsonWriter(memoryStream);
+
+            writer.WriteStartObject();
+            writer.WriteStartArray("test");
+            JsonSerializer.WriteValue<int>(writer, 1);
+            writer.WriteEndArray();
+            writer.WriteEndObject();
+            writer.Flush();
+
+            string json = Encoding.UTF8.GetString(memoryStream.ToArray());
+            Assert.Equal("{\"test\":[1]}", json);
+        }
+    }
+}
\ No newline at end of file
index 8d9d141..d11a4af 100644 (file)
@@ -85,6 +85,7 @@
     <Compile Include="Serialization\Value.WriteTests.GenericCollections.cs" />
     <Compile Include="Serialization\Value.WriteTests.ImmutableCollections.cs" />
     <Compile Include="Serialization\Value.WriteTests.NonGenericCollections.cs" />
+    <Compile Include="Serialization\WriteValueTests.cs" />
     <Compile Include="TestCaseType.cs" />
     <Compile Include="TestClasses.ClassWithComplexObjects.cs" />
     <Compile Include="Utf8JsonReaderTests.cs" />