Home >Backend Development >C++ >How to Convert JsonElement to a Strongly-Typed Object in System.Text.Json?
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.
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>
<code class="language-csharp">var str = ""; // 一些 JSON 字符串 var jDoc = JsonDocument.Parse(str); var myClass = jDoc.RootElement.GetProperty("SomeProperty").Deserialize<SomeClass>();</code>
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!