In Newtonsoft.Json, the ToObject()
method is typically used to convert JSON tokens into strongly typed objects. However, there is no equivalent method readily available in System.Text.Json.
In .NET 6 and later, extension methods have been added to JsonSerializer
to deserialize objects directly from JsonElement
or JsonDocument
. This allows the following syntax:
<code class="language-csharp">using var jDoc = JsonDocument.Parse(str); var myClass = jDoc.RootElement.GetProperty("SomeProperty").Deserialize<SomeClass>();</code>
For .NET 5 and earlier, a workaround involving writing to an intermediate byte buffer can be used to improve performance:
<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) { if (document == null) throw new ArgumentNullException(nameof(document)); return document.RootElement.ToObject<T>(options); }</code>
Instructions:
JsonDocument
statement for using
as it is freeable. The above is the detailed content of How to Deserialize JSON Elements to Objects in System.Text.Json?. For more information, please follow other related articles on the PHP Chinese website!