Json.NET is a third party library which helps conversion between JSON text and .NET object using the JsonSerializer. The JsonSerializer converts .NET objects into their JSON equivalent text and back again by mapping the .NET object property names to the JSON property names. It is open source software and free for commercial purposes.
The following are some awesome【极好的】 features,
Flexible JSON serializer for converting between .NET objects and JSON. LINQ to JSON for manually reading and writing JSON. High performance, faster than .NET's built-in【内嵌】 JSON serializers. Easy to read JSON. Convert JSON to and from XML. Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone.
Let’s start learning how to install and implement:
In Visual Studio, go to Tools Menu -> Choose Library Package Manger -> Package Manager Console. It opens a command window where we need to put the following command to install Newtonsoft.Json.
Install-Package Newtonsoft.Json
OR
In Visual Studio, Tools menu -> Manage Nuget Package Manger Solution and type “JSON.NET” to search it online. Here's the figure,
//使用Json.NET类库需要引入的命名空间 //----------------------------------------------------------------------------- using Newtonsoft.Json; //------------------------------------------------------------------------- #region 3.Json.NET序列化 List<Student> lstStuModel = new List<Student>() { new Student(){ID=1,Name="张飞",Age=250,Sex="男"}, new Student(){ID=2,Name="潘金莲",Age=300,Sex="女"} }; //Json.NET序列化 string jsonData = JsonConvert.SerializeObject(lstStuModel); Console.WriteLine(jsonData); Console.ReadKey(); //Json.NET反序列化 string json = @"{ 'Name':'C#','Age':'3000','ID':'1','Sex':'女'}"; Student descJsonStu = JsonConvert.DeserializeObject<Student>(json);//反序列化 Console.WriteLine(string.Format("反序列化: ID={0},Name={1},Sex={2},Sex={3}", descJsonStu.ID, descJsonStu.Name, descJsonStu.Age, descJsonStu.Sex)); Console.ReadKey(); #endregion运行之后,结果是:
总结:最后还是尽量使用JSON.NET来序列化和反序列化,性能好。
In this article we discussed about how many ways we can implement serialization/deserialization in C#. However JSON.NET wins over other implementations because it facilitates more functionality of JSON validation, JSON schema, LINQ to JSON etc. So use JSON.NET always.