Home > Backend Development > C++ > How to Deserialize JSON Elements to Objects in System.Text.Json?

How to Deserialize JSON Elements to Objects in System.Text.Json?

Linda Hamilton
Release: 2025-01-08 15:42:40
Original
973 people have browsed it

How to Deserialize JSON Elements to Objects in System.Text.Json?

Deserialization of System.Text.Json elements

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.

Solution for .NET 6

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>
Copy after login

Workaround for .NET 5 and earlier versions

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>
Copy after login

Instructions:

  • Remember to use the JsonDocument statement for using as it is freeable.
  • This workaround is available in .NET Core 3.1 and higher.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template