Home >Backend Development >C++ >How to Convert a JsonElement or JsonDocument to an Object in System.Text.Json?

How to Convert a JsonElement or JsonDocument to an Object in System.Text.Json?

Linda Hamilton
Linda HamiltonOriginal
2025-01-08 15:47:41294browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn