In .NET Core 3 and above, method to convert JsonElement to object
This article explores how to convert System.Text.Json
to an object using JsonElement
in .NET Core 3 and above. System.Text.Json
is the new JSON processing library in .NET Core 3.0 and it does not contain an equivalent of the Json.NET
method in ToObject()
which allows converting JToken
to a class.
.NET 6 and above:
Starting with .NET 6, JsonSerializer
provides extension methods to deserialize directly from JsonElement
or JsonDocument
:
<code class="language-csharp">public static TValue? Deserialize<TValue>(this JsonDocument document, JsonSerializerOptions? options = null); public static object? Deserialize(this JsonDocument document, Type returnType, JsonSerializerOptions? options = null);</code>
Using these methods you can easily deserialize objects from JsonElement
:
<code class="language-csharp">var myClass = jDoc.RootElement.GetProperty("SomeProperty").Deserialize<MyClass>();</code>
.NET 5 and earlier:
In earlier versions of .NET, these methods were not available. The workaround is to write the JSON to an intermediate byte buffer:
<code class="language-csharp">public static partial class JsonExtensions { 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); } }</code>
This method performs better than converting JsonElement
to a string first.
Note:
JsonDocument
: JsonDocument
uses pooled memory, so it needs to be released properly (it is recommended to use the using
statement). JsonNode
: Similar methods exist for the mutable JSON document node JsonNode
. The above is the detailed content of How to Convert a JsonElement to an Object in .NET's System.Text.Json?. For more information, please follow other related articles on the PHP Chinese website!