Пример #1
0
 public static void TestDeepCopy()
 {
     using (JsonDocument document = JsonDocument.Parse(jsonSampleString))
     {
         JsonNode node = JsonNode.DeepCopy(document.RootElement);
         CheckNode(node);
     }
 }
Пример #2
0
        public static void TestCloneJsonNodeInJsonElement()
        {
            var jsonObject = new JsonObject
            {
                { "text", "value" },
                { "boolean", true },
                { "array", new JsonArray {
                      "value1", "value2"
                  } }
            };

            JsonElement jsonElement = jsonObject.AsJsonElement();

            var jsonObjectCloneFromElement = (JsonObject)JsonNode.DeepCopy(jsonElement);

            Assert.Equal(3, jsonObjectCloneFromElement.GetPropertyNames().Count);
            Assert.Equal(3, jsonObjectCloneFromElement.GetPropertyValues().Count);

            Assert.Equal("value", jsonObjectCloneFromElement["text"]);
            Assert.Equal(true, jsonObjectCloneFromElement["boolean"]);

            // Modifying should not change the clone and vice versa:

            jsonObjectCloneFromElement["boolean"] = false;
            Assert.Equal(false, jsonObjectCloneFromElement["boolean"]);
            Assert.Equal(true, jsonObject["boolean"]);

            jsonObjectCloneFromElement.GetJsonArrayPropertyValue("array").Add("value3");
            Assert.Equal(3, jsonObjectCloneFromElement.GetJsonArrayPropertyValue("array").Count);
            Assert.Equal(2, jsonObject.GetJsonArrayPropertyValue("array").Count);

            jsonObject["text"] = "different value";
            Assert.Equal("different value", jsonObject["text"]);
            Assert.Equal("value", jsonObjectCloneFromElement["text"]);

            jsonObject.GetJsonArrayPropertyValue("array").Remove("value2");
            Assert.Equal(1, jsonObject.GetJsonArrayPropertyValue("array").Count);
            Assert.Equal(3, jsonObjectCloneFromElement.GetJsonArrayPropertyValue("array").Count);
        }
Пример #3
0
        public static void TestDeepCopyDoesNotOverflow()
        {
            var builder = new StringBuilder();

            for (int i = 0; i < 2_000; i++)
            {
                builder.Append("[");
            }

            for (int i = 0; i < 2_000; i++)
            {
                builder.Append("]");
            }

            var options = new JsonDocumentOptions {
                MaxDepth = 5_000
            };

            using (JsonDocument dom = JsonDocument.Parse(builder.ToString(), options))
            {
                JsonNode node = JsonNode.DeepCopy(dom.RootElement);
            }
        }