Combining multiple untyped JSONs

Usually, before manipulating JSON inputs, you first deserialize them into strongly typed objects that match their structure. However, that might not always be possible. Recently, I had to combine multiple JSON inputs into a single JSON array, without any knowledge of the input JSON structure.

@DamirArh Have you considered just using System.Text.Json.JsonArray and parsing using JsonNode.Parse()? You avoid the overhead of going via Serializer that way.

Something like:

@ythos @DamirArh I agree. The nodes API is definitely the way you want to go here, especially if your end goal is manipulating the data before deserialization.
@gregsdennis @ythos Why would JsonNode.Parse() have less overhead than JsonSerialize.Deserialize<JsonElement>()? They both deserialize text into objects (JsonNode or JsonElement, respectively). I chose JsonElement over JsonNode because I didn't think I needed a mutable object in my case, as suggested here: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/handle-overflow?pivots=dotnet-8-0#deserialize-into-jsonelement-or-jsonnode
How to handle overflow JSON or use JsonElement or JsonNode in System.Text.Json - .NET

Learn how to handle overflow JSON or use JsonElement or JsonNode while using System.Text.Json to serialize and deserialize JSON in .NET.

@DamirArh @ythos your blog post starts out with the premise of manipulating JSON. If you're not actually doing that, then JsonElement is fine.

Under the hood, parsing JsonNode just parses JsonElement anyway. The difference is allocation of the editable DOM.

I'd still prefer JsonDocument.Parse() over serialization, though.

@gregsdennis @ythos Any particular reason you prefer JsonDocument.Parse() over JsonSerializer?

I'm genuinely curious and want to learn.

@DamirArh @gregsdennis If you go through the JsonSerializer code path, you go through GetTypeInfo for the serializer context.

https://github.com/dotnet/runtime/blob/41dbe9c916319d5228d56edaa5c99a0ab6269325/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs#L47

This ultimately resolves to the JsonElementConverter - which calls JsonElement.ParseValue()

https://github.com/dotnet/runtime/blob/41dbe9c916319d5228d56edaa5c99a0ab6269325/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/JsonElementConverter.cs#L10

It's just a much shorter codepath to use JsonDocument/JsonElement/JsonNode directly.

runtime/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs at 41dbe9c916319d5228d56edaa5c99a0ab6269325 · dotnet/runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps. - dotnet/runtime

GitHub
@DamirArh @gregsdennis I'd also argue that it expresses your intent more directly. You want a JsonElement from a probably-JSON string. There's a direct and specific way of doing that.