Newtonsoft has six super-simple and practical features that deserve a try.

One: Storytelling

After reading the official documents and reading some Newtonsoft source code, I have a new understanding of it. First, I summarize six super-classical and practical features and share them with you. Say nothing more. Let's have a look at them.

2. Characteristic analysis

1. Code Formatting

If you use it directly JsonConvert.SerializeObject By default, all json s are squeezed together and are particularly difficult to read, as follows:


        static void Main(string[] args)
        {
            var reportModel = new ReportModel()
            {
                ProductName = "French mini-design dress Slim pure white fairy dress",
                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; }
    }

Then what shall I do?One is provided in JsonConvert Formatting.Indented Used to format json so that it is very friendly during debug, as follows:

2. Kick fields that are not assigned

If you've written about back-end services that provide data to App, I'm sure you're particularly sensitive to the term mobile traffic. There are often more than a dozen fields in a Model, but there may be only three or four fields that need to be passed to App, which causes a huge waste of traffic, as shown below:


        static void Main(string[] args)
        {
            var reportModel = new ReportModel()
            {
                ProductName = "French mini-design dress Slim pure white fairy dress",
                TotalPayment = 100
            };

            var json = JsonConvert.SerializeObject(reportModel, Formatting.Indented);

            System.Console.WriteLine(json);
        }

As you can see from the diagram, the two fields TotalCustomerCount and TotalProductCount are unnecessary and are available in Netnewsoft DefaultValueHandling.Ignore Exclude the enumeration of default values, which is too practical, and make the following modifications:


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

3. Humps compatible with other languages, serpentine nomenclature

Each programming language has its own preferences for naming, such as hump naming in js. I've seen the most serpentine naming in mysql, and the properties we serialize in C# usually start with uppercase letters, such as the fields in Feature 2. There's a problem here. Is there a way to make it compatible for JS to useHump, use snake for mysql, it looks friendly to others, isn't it?πŸ˜„πŸ˜„πŸ˜„Next, let's see how to transform it.

  • Camel Name CamelCaseProperty NamesContractResolver

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

  • Snake Named SnakeCaseNamingStrategy

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

4. Name of custom attribute

If you have docked with third-party systems, you will often encounter this problem. For OpenTaobao, my Model can't always be defined as it does in its documentation, and field names can't be exactly the same, as shown in the following figure:

So there must be a Mapping process here, which you can do with JsonProperty -> propertyName. For demonstration purposes, I'll use reportModel instead.


    static void Main(string[] args)
    {
        var json = "{'title':'French mini-design dress Slim pure 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; }
    }

5. Forward and reverse culling of fields

Maybe some friends don't know these two concepts very well. Here I just show ProductName in Model as an example to explain:

  • Forward culling: all are displayed by default, manual kicking is not shown, use MemberSerialization.OptOut Cooperate with JsonIgnore

         static void Main(string[] args)
        {
            var reportModel = new ReportModel()
            {
                ProductName = "French mini-design dress Slim pure white fairy dress",
                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; }
    }

  • Reverse culling: Do not show by default, manually specify to show, use MemberSerialization.OptIn Cooperate with JsonProperty
       
    [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; }
    }

6. Multiple json s merged into one Model

<font color="red">This feature broke my perception of Newtonsoft, don't you know?</font>Usually we all think that a JSON corresponds to a model, a model corresponds to a json, and even more jsons correspond to a model. That's interesting. Scenes can be thought of by themselves. Here you can easily do this using the PopulateObject method, and see how to write this code:


        static void Main(string[] args)
        {
            var json1 = "{'ProductName':'French mini-design dress Slim pure white fairy dress'}";
            var json2 = "{'TotalCustomerCount':1000,'TotalPayment':100.0,'TotalProductCount':10000}";

            var reportModel = new ReportModel();

            JsonConvert.PopulateObject(json1, reportModel);
            JsonConvert.PopulateObject(json2, reportModel);
        }

Does it mean something?πŸ˜„πŸ˜„πŸ˜„

Three: Summary

In order to avoid affecting your reading experience, this article first summarizes six items for everyone to enjoy. Newtonsoft is really a powerful item. There are too many things to dig. I hope this article will help you. Thank you.

Tags: C# JSON MySQL Mobile Programming

Posted on Sat, 20 Jun 2020 21:28:17 -0400 by j.smith1981