欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

.NET?6新特性試用之System.Text.Json功能改進

 更新時間:2022年03月15日 10:54:04   作者:My?IO  
這篇文章主要介紹了.NET?6新特性試用之System.Text.Json功能改進,

前言:

??System.Text.Json??作為.NET默認的JSON序列化和反序列化類庫,讓我們看看,在.NET 6中有哪些功能上的改進?

Demo

?1.屬性排序?

在屬性上聲明??JsonPropertyOrderAttribute??來控制屬性序列化的順序,而以前,順序是由反射順序決定的,是不確定的。

示例代碼如下:

public class User
{
? ? public int Age { get; set; }

? ? [JsonPropertyOrder(1)]
? ? public string Name { get; set; }
?
? ? [JsonPropertyOrder(-1)]
? ? public int Id { get; set; }
}

排序值較小的數(shù)字首先被序列化;沒有聲明屬性的默認排序值為0:

{
? "Id": 1,
? "Age": 20,
? "Name": "My IO"
}

?2.序列化通知?

??System.Text.Json??新增了4個接口:

  • IJsonOnDeserialized
  • IJsonOnDeserializing
  • IJsonOnSerialized
  • IJsonOnSerializing

從名字上也可以看出它們的作用,即在序列化/反序列化前后被調(diào)用。

示例代碼如下:

public class User : ?IJsonOnSerialized, IJsonOnDeserialized
{
? ? public void OnDeserialized() => this.Validate(); // 反序列化后調(diào)用
? ? public void OnSerializing() => this.Validate(); // 序列化前調(diào)用

? ? private void Validate()
? ? {
? ? ? ? if (this.Age <= 0)
? ? ? ? ? ? throw new ArgumentException();
? ? }
}

結(jié)論:

  • ?“屬性排序”功能有點雞肋,目前還沒碰到過需要指定排序的應用場景。?
  • ?“序列化通知”功能對于設(shè)置默認值和驗證屬性值合法性非常有用。?

到此這篇關(guān)于.NET 6新特性試用之System.Text.Json功能改進的文章就介紹到這了,更多相關(guān) System.Text.Json功能改進內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論