What is the improvement in the System.Text.Json function of .NET 6?
This article mainly introduces "what is the improvement of the System.Text.Json function of .NET 6". In the daily operation, I believe that many people have doubts about the improvement of the System.Text.Json function of .NET 6. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubt about "what improvement is there in the System.Text.Json function of .NET 6?" Next, please follow the editor to study!
Demo1. Attribute sort
Declare JsonPropertyOrderAttribute on attributes to control the order in which attributes are serialized, whereas previously, the order was determined by the reflection order and was uncertain.
The sample code is as follows:
Public class User {public int Age {get; set;} [JsonPropertyOrder (1)] public string Name {get; set;} [JsonPropertyOrder (- 1)] public int Id {get; set;}}
Numbers with lower sort values are serialized first; the default sort value for undeclared attributes is 0:
{"Id": 1, "Age": 20, "Name": "My IO"} 2. Serialization notification
Four new APIs have been added to System.Text.Json:
IJsonOnDeserialized
IJsonOnDeserializing
IJsonOnSerialized
IJsonOnSerializing
Their role can also be seen from the names, that is, they are called before and after serialization / deserialization.
The sample code is as follows:
Public class User: IJsonOnSerialized, IJsonOnDeserialized {public void OnDeserialized () = > this.Validate (); / / call public void OnSerializing () = > this.Validate () after deserialization; / / call private void Validate () {if (this.Age) before serialization