JSON作为一种轻量级的数据交换格式,简单灵活,被很多系统用来数据交互,作为一名.NET开发人员,JSON.NET无疑是最好的序列化框架,支持XML和JSON序列化,高性能,免费开源,支持LINQ查询。目前已被微软集成于webapi框架之中,因此,熟练掌握JSON.NET相当重要,这篇文章是零度参考官网整理的示例,通过这些示例,可以全面了解JSON.NET提供的功能。
Newtonsoft.Json的地址:
官网:http://json.codeplex.com/
源码地址:https://github.com/JamesNK/Newtonsoft.Json
Newtonsoft.Json.dll下载:https://github.com/JamesNK/Newtonsoft.Json/releases
1、使用Newtonsoft.Json(JSON.NET)序列化对象,通过Newtonsoft.Json.Formatting将json格式化输出。
Account account = new Account { Email = "1930906722@qq.com", Active = true, CreatedDate =DateTime.Now, Roles = new List<string> { "User", "Admin" } }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(account, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
public class Account { public string Name { get; set; } public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
执行结果:
2、使用Newtonsoft.Json(JSON.NET)序列化List集合:
List<string> videogames = new List<string> { "HTML5", "JavaScript", ".net","c#",".net core" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(videogames); Console.WriteLine(json);
执行结果:
3、使用Newtonsoft.Json(JSON.NET)序列化dictionary字典
System.Collections.Generic.Dictionary<string, string> dic = new System.Collections.Generic.Dictionary<string, string> { { "Name", "张三" }, { "Age", "20" }, { "Email", "193090622@qq.com" } }; string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(dic, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json1); Console.WriteLine(""); Console.WriteLine("未格式化的json:"); string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(dic, Newtonsoft.Json.Formatting.None); Console.WriteLine(json2);
执行结果:
4、Newtonsoft.Json(JSON.NET)将序列化结果保存到指定的文件:
User movie = new User { Name = "张三", Age = 1993 }; using (System.IO.StreamWriter file = System.IO.File.CreateText(@"F:\UserInfo.txt")) { Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); serializer.Serialize(file, movie); }
public class User { public string Name { set; get; } public int Age { set; get; } }
执行后保存到文件的结果:
5、Newtonsoft.Json(JSON.NET)基于枚举类型的JsonConverters转换器
List<JosnEnum> list = new List<JosnEnum> { JosnEnum.NotStartus, JosnEnum.Startus }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(list); Console.WriteLine(json); Console.WriteLine(""); System.Collections.Generic.Dictionary<string, int> dic = new System.Collections.Generic.Dictionary<string, int> { {((JosnEnum)(int)JosnEnum.NotStartus).ToString() ,(int)JosnEnum.NotStartus} , {((JosnEnum)(int)JosnEnum.Startus).ToString() ,(int)JosnEnum.Startus} }; string dicJson = Newtonsoft.Json.JsonConvert.SerializeObject(dic); Console.WriteLine(dicJson); Console.WriteLine(""); List&l