C#中实现Json序列化与反序列化的几种方式

2019-12-30 15:01:42刘景俊

#region 2.JavaScriptSerializer方式实现序列化和反序列化
   Student stu = new Student()
    {
     ID = 1,
     Name = "关羽",
     Age = 2000,
     Sex = "男"
    };

   JavaScriptSerializer js = new JavaScriptSerializer();
   string jsonData = js.Serialize(stu);//序列化
   Console.WriteLine(jsonData);


   ////反序列化方式一:
   string desJson = jsonData;
   //Student model = js.Deserialize<Student>(desJson);// //反序列化
   //string message = string.Format("ID={0},Name={1},Age={2},Sex={3}", model.ID, model.Name, model.Age, model.Sex);
   //Console.WriteLine(message);
   //Console.ReadKey(); 


   ////反序列化方式2
   dynamic modelDy = js.Deserialize<dynamic>(desJson); //反序列化
   string messageDy = string.Format("动态的反序列化,ID={0},Name={1},Age={2},Sex={3}",
    modelDy["ID"], modelDy["Name"], modelDy["Age"], modelDy["Sex"]);//这里要使用索引取值,不能使用对象.属性
   Console.WriteLine(messageDy);
   Console.ReadKey(); 
   #endregion 

结果是:

 C#,json,反序列化,json序列化和反序列化,c,序列化

最后看看使用JSON.NET的情况,引入类库:

C#,json,反序列化,json序列化和反序列化,c,序列化

下面的英文,看不懂可略过。。。

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,

C#,json,反序列化,json序列化和反序列化,c,序列化