在.Net Core 3.0中尝试新的System.Text.Json API .NET https://www.cnblogs.com/muran/p/11770629.html
.NET Core 3.0提供了一个名为System.Text.Json的全新命名空间,它支持reader/writer,文档对象模型(DOM)和序列化程序。在此博客文章中,我将介绍它如何工作以及如何使用。
获取JSON库
- 如果以.NET Core为目标,请安装.NET Core 3.0及以上版本,该版本提供了新的JSON库和ASP.NET Core集成。
- 如果以.NET Standard或.NET Framework为目标。安装System.Text.Json NuGet软件包(确保安装.NET Framework4.6.0或更高版本)。为了与ASP.NET Core集成,必须以.NET Core 3.0为目标。
NET Core 3.0中JSON特性
新的JSON API通过使用Span进行性能优化,并且可以直接处理UTF-8,而无需转码为UTF-16 string 实例。这两个方面对于ASP.NET Core都是至关重要的,在ASP.NET Core中,吞吐量是关键要求。使用System.Text.Json,可以将速度提高大约1.3倍至5倍。
使用System.Text.Json
using System.Text.Json; using System.Text.Json.Serialization;
使用序列化器Serializer
- 学习.Net Core最好的方式是查看源码,下面是JsonSerializer Serialize的部分源码:
namespace System.Text.Json { public static partial class JsonSerializer { /// <summary> /// Convert the provided value into a <see cref="System.String"/>. /// </summary> /// <returns>A <see cref="System.String"/> representation of the value.</returns> /// <param name="value">The value to convert.</param> /// <param name="options">Options to control the conversion behavior.</param> /// <remarks>Using a <see cref="System.String"/> is not as efficient as using UTF-8 /// encoding since the implementation internally uses UTF-8. See also <see cref="SerializeToUtf8Bytes"/> /// and <see cref="SerializeAsync"/>. /// </remarks> public static string Serialize<TValue>(TValue value, JsonSerializerOptions options = null) { return ToStringInternal(value, typeof(TValue), options); } /// <summary> /// Convert the provided value into a <see cref="System.String"/>. /// </summary> /// <returns>A <see cref="System.String"/> representation of the value.</returns> /// <param name="value">The value to convert.</param> /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param> /// <param name="options">Options to control the conversion behavior.</param> /// <remarks>Using a <see cref="System.String"/> is not as efficient as using UTF-8