Description
Adding a JsonElement via JsonArray.Add throws an exception with .NET 8. In .NET 7 it worked without throwing.
It is interesting that JsonArray.Add worked in .NET 7 but JsonValue.Create fails in both .NET 7/8 when passing in a JsonElement with ValueKind.Object/Array.
Related: #70427
Regression in 1db4357 ?
Reproduction Steps
using System.Text.Json;
using System.Text.Json.Nodes;
var element = JsonDocument.Parse("""{"test":"hello world"}""");
var array = new JsonArray();
array.Add(element.RootElement); // .NET 8.0 throws here
Console.WriteLine(array.ToJsonString());
Expected behavior
Works without exception.
Actual behavior
Throws a System.InvalidOperationException: "The element cannot be an object or array."
bei System.Text.Json.ThrowHelper.ThrowInvalidOperationException_NodeElementCannotBeObjectOrArray()
bei System.Text.Json.Nodes.JsonValue.VerifyJsonElementIsNotArrayOrObject(JsonElement& element)
bei System.Text.Json.Nodes.JsonValue.Create[T](T value, Nullable`1 options)
bei System.Text.Json.Nodes.JsonArray.Add[T](T value)
Regression?
Yes, it works with .NET 7.0
Known Workarounds
For this particular case the JsonDocument could be added instead of the RootElement.
A general workaround would be #70427 (comment)
Configuration
.NET 8
Windows
x64
Other information
No response
Description
Adding a
JsonElementviaJsonArray.Addthrows an exception with .NET 8. In .NET 7 it worked without throwing.It is interesting that
JsonArray.Addworked in .NET 7 butJsonValue.Createfails in both .NET 7/8 when passing in aJsonElementwithValueKind.Object/Array.Related: #70427
Regression in 1db4357 ?
Reproduction Steps
Expected behavior
Works without exception.
Actual behavior
Throws a System.InvalidOperationException: "The element cannot be an object or array."
Regression?
Yes, it works with .NET 7.0
Known Workarounds
For this particular case the
JsonDocumentcould be added instead of theRootElement.A general workaround would be #70427 (comment)
Configuration
.NET 8
Windows
x64
Other information
No response