/* github */

C#中Unity对象的注册方式与生命周期解析

  • 示例代码

 1 static void Main(string[] args)
 2         {
 3             {
 4                 Console.WriteLine("----------全局设置----------");
 5                 Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
 6                 JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
 7                 {
 8                     //日期类型默认格式化处理
 9                     setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
10                     setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
11                     //空值处理
12                     setting.NullValueHandling = NullValueHandling.Ignore;
13                     //Bool类型转换设置
14                     setting.Converters.Add(new BoolConvert("是,否"));
15                     return setting;
16                 });
17 
18                 List<User> users = new List<User>() {
19                 new User{ UserName = "wjl",Age =22,State = UserState.Deleted,Email="131565452@qq.com" },
20                 new User{ UserName = "hyf",Age =22,State = UserState.Normal ,Email="456461@qq.com"}
21             };
22                 var resUserJson = JsonConvert.SerializeObject(users);
23                 Console.WriteLine(resUserJson);
24             }
25 
26 
27             {
28                 Console.WriteLine("----------设置忽略为空的属性----------");
29                 User user = new User { UserName = "ljm", Age = 22, State = UserState.Normal };
30                 JsonSerializerSettings jsetting = new JsonSerializerSettings();
31                 jsetting.NullValueHandling = NullValueHandling.Ignore; //设置忽略为空的属性 , Email 将不显示
32                 Console.WriteLine(JsonConvert.SerializeObject(user, Formatting.Indented, jsetting));
33             }
34 
35             {
36                 Console.WriteLine("----------自定义显示的字段----------");
37                 Student stu = new Student { stuName = "ljm", className = "计算机1班" };
38                 JsonSerializerSettings jsetting_stu = new JsonSerializerSettings();
39                 jsetting_stu.ContractResolver = new LimitPropsContractResolver(new string[] { "stuName" }, false);
40                 Console.WriteLine(JsonConvert.SerializeObject(stu, Formatting.Indented, jsetting_stu));
41             }
42 
43             Console.ReadLine();
44 
45         }
  • 运行效果

 

posted on 2019-06-01 01:38  王精灵  阅读(634)  评论(0编辑  收藏  举报