Home >Backend Development >C++ >How to Convert a JsonElement or JsonDocument to an Object in System.Text.Json?
Equivalent function in System.Text.Json
The Json.NET framework provides a ToObject()
method to convert JToken to a class. However, there is no direct equivalent of this method in System.Text.Json.
Workaround for .NET 6 and above
In .NET 6, extension methods were introduced that allow objects to be deserialized directly from a JsonElement or JsonDocument. These methods are:
<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>
Example:
<code class="language-csharp">using var jDoc = JsonDocument.Parse(str); var myClass = jDoc.RootElement.GetProperty("SomeProperty").Deserialize<SomeClass>();</code>
Workaround for .NET 5 and earlier
In .NET 5 and earlier, these extension methods do not exist. Please consider using the following workarounds:
<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>
The above is the detailed content of How to Convert a JsonElement or JsonDocument to an Object in System.Text.Json?. For more information, please follow other related articles on the PHP Chinese website!