<PackageReference Include="System.Text.Json" Version="6.0.10" />

LargeJsonObjectExtensionDataSerializationState

Implements a mitigation for deserializing large JsonObject extension data properties. Extension data properties use replace semantics when duplicate keys are encountered, which is an O(n) operation for JsonObject resulting in O(n^2) total deserialization time. This class mitigates the performance issue by storing the deserialized properties in a temporary dictionary (which has O(1) updates) and copies them to the destination object at the end of deserialization.
using System.Collections.Generic; using System.Text.Json.Nodes; namespace System.Text.Json.Serialization.Converters { internal sealed class LargeJsonObjectExtensionDataSerializationState { public const int LargeObjectThreshold = 25; private readonly Dictionary<string, JsonNode> _tempDictionary; public JsonObject Destination { get; } public LargeJsonObjectExtensionDataSerializationState(JsonObject destination) { StringComparer comparer = (destination.Options?.PropertyNameCaseInsensitive ?? false) ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; Destination = destination; _tempDictionary = new Dictionary<string, JsonNode>(comparer); } public void AddProperty(string key, JsonNode value) { _tempDictionary[key] = value; } public void Complete() { foreach (KeyValuePair<string, JsonNode> item in _tempDictionary) { Destination[item.Key] = item.Value; } } } }