JSON

在C#中,Json的序列化和反序列化的几种方式总结(2)

字号+ 作者:H5之家 来源:H5之家 2016-07-26 10:03 我要评论( )

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

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.

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • GSON实现Java对象的JSON序列化与反序列化的实例教程

    GSON实现Java对象的JSON序列化与反序列化的实例教程

    2016-06-28 13:00

  • serialize序列化和json

    serialize序列化和json

    2016-05-26 10:04

  • C#序列化和反序列化综合案例

    C#序列化和反序列化综合案例

    2016-05-08 14:06

  • DataSnap与JSON序列化3

    DataSnap与JSON序列化3

    2016-01-18 18:00

网友点评
l