前言:
??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; } }
排序值较小的数字首先被序列化;没有声明属性的默认排序值为0:
{ ? "Id": 1, ? "Age": 20, ? "Name": "My IO" }
?2.序列化通知?
??System.Text.Json??新增了4个接口:
IJsonOnDeserialized IJsonOnDeserializing IJsonOnSerialized IJsonOnSerializing从名字上也可以看出它们的作用,即在序列化/反序列化前后被调用。
示例代码如下:
public class User : ?IJsonOnSerialized, IJsonOnDeserialized { ? ? public void OnDeserialized() => this.Validate(); // 反序列化后调用 ? ? public void OnSerializing() => this.Validate(); // 序列化前调用 ? ? private void Validate() ? ? { ? ? ? ? if (this.Age <= 0) ? ? ? ? ? ? throw new ArgumentException(); ? ? } }
结论: ?[属性排序]功能有点鸡肋,目前还没碰到过需要指定排序的应用场景。? ?[序列化通知]功能对于设置默认值和验证属性值合法性非常有用。?
到此这篇关于.NET 6新特性试用之System.Text.Json功能改进的文章就介绍到这了,更多相关 System.Text.Json功能改进内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
查看更多关于.NET 6新特性试用之System.Text.Json功能改进的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did19433