One: Tell stories

After reading the official documentation, I have read some Newtonsoft source code, which has a new understanding of it. First, I summarize six super classic and practical features, and share with you

Two: characteristic analysis

1. Code formatting

If you directly use JsonConvert SerializeObject, by default all is squeezing in a json, special is not convenient to read, as shown below:

Static void Main(string[] args) {var reportModel = new reportModel () {ProductName = "", TotalPayment = 100, TotalCustomerCount = 2, TotalProductCount = 333 }; var json = JsonConvert.SerializeObject(reportModel); System.Console.WriteLine(json); } } public class ReportModel { public string ProductName { get; set; } public int TotalCustomerCount { get; set; } public decimal TotalPayment { get; set; } public int TotalProductCount { get; set; }}Copy the code

So what to do? JsonConvert provides a Formatting.Indented to format JSON, which is very friendly during debugging, as follows:

2. Remove fields that are not assigned values

If you have ever written a back-end service that provides data for App, I believe you are particularly sensitive to the word mobile phone traffic. There are often a dozen fields on a Model, but only three or four fields need to be transmitted to App, which causes huge traffic waste, as shown in the following figure:

Static void Main(string[] args) {var reportModel = new reportModel () {ProductName = "", TotalPayment = 100 }; var json = JsonConvert.SerializeObject(reportModel, Formatting.Indented); System.Console.WriteLine(json); }Copy the code

Can be seen in the figure, TotalCustomerCount and TotalProductCount these two fields is unnecessary, provide a DefaultValueHandling Netnewsoft. Ignore rejecting the default value of enumeration, very practical, The transformation is as follows:


            var json = JsonConvert.SerializeObject(reportModel, Formatting.Indented,
                                                   new JsonSerializerSettings
                                                   {
                                                       DefaultValueHandling = DefaultValueHandling.Ignore
                                                   });
Copy the code

3. Hump and snake nomenclature compatible with other languages

Every programming language has its own preference for nomenclature. For example, js likes to use the camel’s name, I see the snake nomenclature most often in mysql, and the properties we serialize in C# tend to start with a capital letter, like the fields you see in feature 2. There is no way to compatible, give JS to use the hump, give mysql to use the snake, so it appears to others some friendly, isn’t it 😄😄😄, next look at how to change.

  • Hump named CamelCasePropertyNamesContractResolver

            var json = JsonConvert.SerializeObject(reportModel, Formatting.Indented,
                                                   new JsonSerializerSettings
                                                   {
                                                       ContractResolver = new CamelCasePropertyNamesContractResolver()
                                                   });
Copy the code

  • Snake named SnakeCaseNamingStrategy

            var json = JsonConvert.SerializeObject(reportModel, Formatting.Indented,
                                                   new JsonSerializerSettings
                                                   {
                                                       ContractResolver = new DefaultContractResolver()
                                                       {
                                                           NamingStrategy = new SnakeCaseNamingStrategy()
                                                       }
                                                   });
Copy the code

4. Customize the name of the property

If you have done docking development with a third-party system, you will usually encounter this problem. Take OpenTaobao for example, my Model cannot be defined in this way according to its document, and the field name cannot be completely consistent, as shown below:

JsonProperty -> propertyName = JsonProperty -> reportModel = JsonProperty -> propertyName = JsonProperty -> reportModel

static void Main(string[] args) { var json = "{'title':' White Fairy Dress ',' CustomerCount ':1000,' TotalPayment ':100.0,' productCount ':10000}" var reportModel = JsonConvert.DeserializeObject<ReportModel>(json); } public class ReportModel { [JsonProperty("title")] public string ProductName { get; set; } [JsonProperty("customercount")] public int TotalCustomerCount { get; set; } [JsonProperty("totalpayment")] public decimal TotalPayment { get; set; } [JsonProperty("productcount")] public int TotalProductCount { get; set; }}Copy the code

5. Forward and reverse fields are deleted

For those who are not familiar with these two concepts, I will only show ProductName in Model as an example:

  • Forward culling: by default, all displays are displayed. Manually kick out those that are not displayedMemberSerialization.OptOutCooperate withJsonIgnore
Static void Main(string[] args) {var reportModel = new reportModel () {ProductName = "", TotalPayment = 100 }; var json = JsonConvert.SerializeObject(reportModel, Formatting.Indented); System.Console.WriteLine(json); } [JsonObject(MemberSerialization.OptOut)] public class ReportModel { public string ProductName { get; set; } [JsonIgnore] public int TotalCustomerCount { get; set; } [JsonIgnore] public decimal TotalPayment { get; set; } [JsonIgnore] public int TotalProductCount { get; set; }}Copy the code

  • Reverse cull: do not display by default, manually specify to display, useMemberSerialization.OptInCooperate withJsonProperty
[JsonObject(MemberSerialization.OptIn)] public class ReportModel { [JsonProperty] public string ProductName { get; set; } public int TotalCustomerCount { get; set; } public decimal TotalPayment { get; set; } public int TotalProductCount { get; set; }}Copy the code

6. Merge multiple JSON files into one Model

This feature broke my perception of Newtonsoft at the beginning. What about you? We usually think that one JSON corresponds to one model, and one model corresponds to one JSON. It is interesting that multiple JSON corresponds to one model. The PopulateObject method will do the trick for you. Here’s how to write this code:

Static void Main(string[] args) {var json1 = "{'ProductName':' ProductName'}"; Var json2 = "{' TotalCustomerCount: 1000, 'TotalPayment: 100.0,' TotalProductCount: 10000}"; var reportModel = new ReportModel(); JsonConvert.PopulateObject(json1, reportModel); JsonConvert.PopulateObject(json2, reportModel); }Copy the code

😄😄😄

Three:

In order not to affect the reading experience, this article summarizes six for everyone to enjoy, Newtonsoft is really powerful, there are too many things to discover, I hope this article can help you, thank you.