[C#][Newtonsoft.Json] Newtonsoft.Json 序列化时的一些其它用法

Newtonsoft.Json 序列化时的一些其它用法

  在进行序列化时我们一般会选择使用匿名类型 new { },或者添加一个新类(包含想输出的所有字段)。但不可避免的会出现以下情形:如属性值隐藏(敏感信息过滤、保密或节约流量等原因)、重命名字段和输出结果格式化等额外操作。

Nuget

<packages>
  <package id="Newtonsoft.Json" version="10.0.3" targetFramework="net47" />
</packages>

常见用法

  User.cs

    public class User
    {
        public Guid Id { get; set; }

        public string Name { get; set; }

        public string Password { get; set; }

        public DateTime Birthday { get; set; }
    }

  Program.cs

        static void Main(string[] args)
        {
            Console.WriteLine(JsonConvert.SerializeObject(new User { Id = Guid.NewGuid(), Name = "Wen", Password = "123", Birthday = DateTime.Now }));

            Console.Read();
        }

其它用法

  字段和属性重命名;隐藏字段和属性;输出结果格式化。

  User.cs

    public class User
    {
        public Guid Id { get; set; }

        [JsonProperty("UserName")]  //重命名
        public string Name { get; set; }

        [JsonIgnore]    //不序列化公共字段或属性值
        public string Password { get; set; }

        [JsonConverter(typeof(IsoDateTimeConverter))]   //转换成 ISO 8601 的日期格式
        public DateTime Birthday { get; set; }
    }

  Program.cs 不变


【参考】http://www.cnblogs.com/wolf-sun/p/5714589.html

原文地址:https://www.cnblogs.com/liqingwen/p/7483392.html