Home >Backend Development >C++ >How to Convert a JsonElement to an Object in .NET's System.Text.Json?

How to Convert a JsonElement to an Object in .NET's System.Text.Json?

Barbara Streisand
Barbara StreisandOriginal
2025-01-08 15:27:401042browse

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:

    Release of
  • JsonDocument: JsonDocument uses pooled memory, so it needs to be released properly (it is recommended to use the using statement).
  • New method availability: New deserialization extension methods are available in .NET 6.0 Preview RC1 and later.
  • Similar methods for
  • JsonNode: Similar methods exist for the mutable JSON document node JsonNode.

How to Convert a JsonElement to an Object in .NET's System.Text.Json?

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!

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