Home >Backend Development >C++ >How to Convert JsonElement to a Strongly-Typed Object in System.Text.Json?

How to Convert JsonElement to a Strongly-Typed Object in System.Text.Json?

Linda Hamilton
Linda HamiltonOriginal
2025-01-08 15:37:46990browse

How to Convert JsonElement to a Strongly-Typed Object in System.Text.Json?

ToObject equivalent method of System.Text.Json.JsonElement

Concept

In .NET Core 3, the Json.NET library provides the ToObject method, allowing JToken objects to be converted to strongly typed classes. This article explores the equivalent method of deserializing JsonElement objects in System.Text.Json.

Solution

In .NET 6 and above:

JsonSerializer has added extension methods to deserialize directly from JsonElement and JsonDocument objects:

<code class="language-csharp">public static TValue? Deserialize<TValue>(this JsonDocument document, JsonSerializerOptions? options = null);
public static TValue? Deserialize<TValue>(this JsonElement element, JsonSerializerOptions? options = null);</code>

In .NET 5 and earlier:

There is a workaround that 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);
}</code>

Example

<code class="language-csharp">var str = ""; // 一些 JSON 字符串
var jDoc = JsonDocument.Parse(str);
var myClass = jDoc.RootElement.GetProperty("SomeProperty").Deserialize<SomeClass>();</code>

Attention

  • Release the JsonDocument object to release memory resources.
  • Extension methods were added to JsonNode in .NET 6 for similar deserialization functionality.
  • The workaround performs better because it avoids unnecessary string conversions.

The above is the detailed content of How to Convert JsonElement to a Strongly-Typed 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