Efficiently Converting JsonElement to a .NET Object
System.Text.Json, introduced in .NET Core 3.0, offers a high-performance JSON handling solution. However, unlike Json.NET, it lacked a direct equivalent to the ToObject
method for convenient conversion of JsonElement
to a .NET object until .NET 6.
.NET 6 and Beyond: Simplified Conversion
.NET 6 and later versions provide built-in extension methods within JsonSerializer
that streamline the process:
<code class="language-csharp">public static TValue? Deserialize<TValue>(this JsonDocument document, JsonSerializerOptions? options = null); public static object? Deserialize(this JsonElement element, Type returnType, JsonSerializerOptions? options = null);</code>
This allows for straightforward conversion:
<code class="language-csharp">using var jDoc = JsonDocument.Parse(jsonString); var myObject = jDoc.RootElement.GetProperty("propertyName").Deserialize<MyObjectType>();</code>
.NET 5 and Earlier: A Practical Workaround
For projects using .NET 5 or earlier versions, which lack these convenient extension methods, a workaround involves writing the JsonElement
to a byte buffer and then deserializing from that buffer:
<code class="language-csharp">public static T ToObject<T>(this JsonElement element, JsonSerializerOptions options = null) { var bufferWriter = new ArrayBufferWriter<byte>(); using (var writer = new Utf8JsonWriter(bufferWriter)) element.WriteTo(writer); return JsonSerializer.Deserialize<T>(bufferWriter.WrittenSpan, options); } public static T ToObject<T>(this JsonDocument document, JsonSerializerOptions options = null) { return document.RootElement.ToObject<T>(options); }</code>
This method avoids the overhead of string or char span conversions, providing an efficient solution for older .NET versions.
The above is the detailed content of How to Efficiently Convert JsonElement to a .NET Object?. For more information, please follow other related articles on the PHP Chinese website!