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

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

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

 

Nuget

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

 

常见用法

  User.csui

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

        public string Name { get; set; }

        public string Password { get; set; }

        public DateTime Birthday { get; set; }
    }

 

  Program.csspa

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

            Console.Read();
        }

 

其它用法

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

 

  User.cscode

    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 不变htm

 

 


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

相关文章
相关标签/搜索