Newtonsoft 六个超简单又实用的特性,值得一试 【上篇】

一:讲故事

看完官方文档,阅读了一些 Newtonsoft 源码,对它有了新的认识,先总结 六个超经典又实用的特性,同大家一起分享,废话不多说,快来一起看看吧~~~

二:特性分析

1. 代码格式化
如果你直接使用 JsonConvert.SerializeObject的话,默认情况下所有的json是挤压在一块的,特别不方便阅读,如下所示:

 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; }
    }

在这里插入图片描述
那怎么办呢? JsonConvert中提供了一个 Formatting.Indented 用来格式化json,这样在 debug 的过程中就非常友好,改造如下:
在这里插入图片描述
2. 踢掉没有被赋值的字段

如果你写过给 App 提供数据的后端服务,我相信你对手机流量这个词特别敏感,往往一个 Model 上有十几个字段,但需要传给 App 可能就 三四个字段,这就造成了巨大的流量浪费,如下图:


        static void Main(string[] args)
        {
            var reportModel = new ReportModel()
            {
                ProductName = "法式小众设计感长裙气质显瘦纯白色仙女连衣裙",
                TotalPayment = 100
            };

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

            System.Console.WriteLine(json);
        }

在这里插入图片描述
从图中可以看到,TotalCustomerCount 和 TotalProductCount 这两个字段就没必要了,Netnewsoft 中提供了 DefaultValueHandling.Ignore 剔除默认值的枚举,太实用了,改造如下:


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

在这里插入图片描述
3. 兼容其他语言的 驼峰,蛇形命名法

每一套编程语言都有各自偏好的命名法,比如 js 中都喜欢采用 驼峰命名法,在 mysql 中我见过最多的 蛇形命名法,而我们在 C# 中序列化的属性一般都是大写字母开头,比如你看到的 特性二 中的字段,那这里就存在问题了,有没有办法兼容一下,给 js 就用 驼峰,给 mysql 就用 蛇形,这样显得对别人友好一些,不是嘛😄😄😄,接下来看看怎么改造。

驼峰命名 CamelCasePropertyNamesContractResolver


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


在这里插入图片描述
蛇形命名 SnakeCaseNamingStrategy

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

在这里插入图片描述
4. 自定义属性的名字

如果你和第三方系统进行过对接开发,通常都会遇到这个问题,就拿 OpenTaobao 来说,我的Model总不能按照它文档这样定义吧,而且字段名称也不可能做到完全一致,如下图:
在这里插入图片描述
所以这里面必然要存在一个 Mapping 的过程,这就可以用 JsonProperty -> propertyName 帮你搞定,为了方便演示,我还是用 reportModel 吧。


    static void Main(string[] args)
    {
        var json = "{'title':'法式小众设计感长裙气质显瘦纯白色仙女连衣裙','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. 对字段的 正向剔除 和 反向剔除

可能有些朋友对这两个概念不是特别了解,这里我仅显示 Model 中的 ProductName 为例讲解一下:

正向剔除: 默认所有都显示,手工踢掉不显示的,使用 MemberSerialization.OptOut 配合 JsonIgnore


 		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; }
    }

在这里插入图片描述
反向剔除: 默认都不显示,手工指定要显示的,使用 MemberSerialization.OptIn 配合 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. 多个json 合并到 一个Model

这个特性当初打破了我对 Newtonsoft 的认知观,不知道您呢? 通常我们都会认为 一个 json 对应一个 model,一个 model 对应一个 json,居然还可以多个 json 对应一个 model 的情况,这就有意思了,场景大家可以自己想一想哈,这里使用 PopulateObject 方法就可以轻松帮你搞定,接下来看看怎么写这个代码:

    static void Main(string[] args)
        {
            var json1 = "{'ProductName':'法式小众设计感长裙气质显瘦纯白色仙女连衣裙'}";
            var json2 = "{'TotalCustomerCount':1000,'TotalPayment':100.0,'TotalProductCount':10000}";

            var reportModel = new ReportModel();

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

在这里插入图片描述
是不是有点意思😄😄😄

三:总结

为了怕影响阅读体验,这一篇就先总结六个供大家欣赏,Newtonsoft 这玩意确实非常强大,太多的东西需要去挖掘,希望本篇对你有帮助,谢谢。

点点关注不迷路,敬请期待下片!!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值