-
1、示例代码
请详细阅读
static void Main(string[] args) { { Console.WriteLine("----------全局设置----------"); Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings(); JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() => { //日期类型默认格式化处理 setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; //空值处理 setting.NullValueHandling = NullValueHandling.Ignore; //Bool类型转换设置 setting.Converters.Add(new BoolConvert("是,否")); return setting; }); List<User> users = new List<User>() { new User{ UserName = "wjl",Age =22,State = UserState.Deleted,Email="131565452@qq.com" }, new User{ UserName = "hyf",Age =22,State = UserState.Normal ,Email="456461@qq.com"} }; var resUserJson = JsonConvert.SerializeObject(users); Console.WriteLine(resUserJson); } { Console.WriteLine("----------设置忽略为空的属性----------"); User user = new User { UserName = "ljm", Age = 22, State = UserState.Normal }; JsonSerializerSettings jsetting = new JsonSerializerSettings(); jsetting.NullValueHandling = NullValueHandling.Ignore; //设置忽略为空的属性 , Email 将不显示 Console.WriteLine(JsonConvert.SerializeObject(user, Formatting.Indented, jsetting)); } { Console.WriteLine("----------自定义显示的字段----------"); Student stu = new Student { stuName = "ljm", className = "计算机1班" }; JsonSerializerSettings jsetting_stu = new JsonSerializerSettings(); jsetting_stu.ContractResolver = new LimitPropsContractResolver(new string[] { "stuName" }, false); Console.WriteLine(JsonConvert.SerializeObject(stu, Formatting.Indented, jsetting_stu)); } Console.ReadLine(); }
-
2、运行效果