I want to know the equivalent of the ToObject<>()
method in Json.NET for System.Text.Json.
Using Json.NET you can use any JToken
and
There is an open enhancement about this, currently targeted for Future:
In the interim you may get better performance by writing to an intermediate byte
buffer rather than to a string, since both JsonDocument
and Utf8JsonReader
work directly with byte
spans rather than strings or char
spans. As stated in the docs:
Serializing to UTF-8 is about 5-10% faster than using the string-based methods. The difference is because the bytes (as UTF-8) don't need to be converted to strings (UTF-16).
public static partial class JsonExtensions
{
public static T ToObject(this JsonElement element, JsonSerializerOptions options = null)
{
var bufferWriter = new ArrayBufferWriter();
using (var writer = new Utf8JsonWriter(bufferWriter))
element.WriteTo(writer);
return JsonSerializer.Deserialize(bufferWriter.WrittenSpan, options);
}
public static T ToObject(this JsonDocument document, JsonSerializerOptions options = null)
{
if (document == null)
throw new ArgumentNullException(nameof(document));
return document.RootElement.ToObject(options);
}
}
Demo fiddle here.