在 .NET 6中,扩展方法被添加到JsonSerializer
直接从 aJsonElement
或反序列化对象JsonDocument
:
public static partial class JsonSerializer
{
public static TValue? Deserialize<TValue>(this JsonDocument document, JsonSerializerOptions? options = null);
public static object? Deserialize(this JsonDocument document, Type returnType, JsonSerializerOptions? options = null);
public static TValue? Deserialize<TValue>(this JsonDocument document, JsonTypeInfo<TValue> jsonTypeInfo);
public static object? Deserialize(this JsonDocument document, Type returnType, JsonSerializerContext context);
public static TValue? Deserialize<TValue>(this JsonElement element, JsonSerializerOptions? options = null);
public static object? Deserialize(this JsonElement element, Type returnType, JsonSerializerOptions? options = null);
public static TValue? Deserialize<TValue>(this JsonElement element, JsonTypeInfo<TValue> jsonTypeInfo);
public static object? Deserialize(this JsonElement element, Type returnType, JsonSerializerContext context);
}
现在您将能够:
using var jDoc = JsonDocument.Parse(str);
var myClass = jDoc.RootElement.GetProperty("SomeProperty").Deserialize<SomeClass>();
笔记:
JsonDocument
是一次性的。根据文档,此类利用池内存中的资源......未能正确处理此对象将导致内存未返回到池中,这将增加框架各个部分的 GC 影响。
所以,一定要声明你jDoc
的using
声明。
新方法应该出现在.NET 6.0 Preview RC1中。
它们是为了响应增强请求而添加的。我们应该能够从已关闭的 DOM #31274 进行序列化和序列化。
在 .NET 5 和更早版本中,这些方法不存在。作为一种解决方法,您可以通过写入中间byte
缓冲区而不是字符串来获得更好的性能,因为两者都JsonDocument
直接Utf8JsonReader
使用byte
跨度而不是字符串或char
跨度。如文档中所述:
序列化为 UTF-8 比使用基于字符串的方法快 5-10%。不同之处在于字节(作为 UTF-8)不需要转换为字符串(UTF-16)。
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);
}
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);
}
}
演示小提琴在这里。