C#中實(shí)現(xiàn)Json序列化與反序列化的幾種方式
什么是JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate. JSON is a text format that is completely language independent.
翻譯:Json【javascript對象表示方法】,它是一個(gè)輕量級的數(shù)據(jù)交換格式,我們可以很簡單的來讀取和寫它,并且它很容易被計(jì)算機(jī)轉(zhuǎn)化和生成,它是完全獨(dú)立于語言的。
Json支持下面兩種數(shù)據(jù)結(jié)構(gòu):
- 鍵值對的集合--各種不同的編程語言,都支持這種數(shù)據(jù)結(jié)構(gòu);
- 有序的列表類型值的集合--這其中包含數(shù)組,集合,矢量,或者序列,等等。
Json有下面幾種表現(xiàn)形式
1.對象
一個(gè)沒有順序的“鍵/值”,一個(gè)對象以花括號“{”開始,并以花括號"}"結(jié)束,在每一個(gè)“鍵”的后面,有一個(gè)冒號,并且使用逗號來分隔多個(gè)鍵值對。
例如:
var user = {"name":"Manas","gender":"Male","birthday":"1987-8-8"}
2.數(shù)組
設(shè)置值的順序,一個(gè)數(shù)組以中括號"["開始,并以中括號"]"結(jié)束,并且所有的值使用逗號分隔
例如:
var userlist = [{"user":{"name":"Manas","gender":"Male","birthday":"1987-8-8"}}, {"user":{"name":"Mohapatra","Male":"Female","birthday":"1987-7-7"}}]
3.字符串
任意數(shù)量的Unicode字符,使用引號做標(biāo)記,并使用反斜杠來分隔。
例如:
var userlist = "{\"ID\":1,\"Name\":\"Manas\",\"Address\":\"India\"}"
好了,介紹完JSON,現(xiàn)在說正題。
序列化和反序列化有三種方式:
- 使用
JavaScriptSerializer
類 - 使用
DataContractJsonSerializer
類 - 使用JSON.NET類庫
我們先來看看使用 DataContractJsonSerializer的情況
DataContractJsonSerializer
類幫助我們序列化和反序列化Json,他在程序集 System.Runtime.Serialization.dll
下的System.Runtime.Serialization.Json
命名空間里。
首先,這里,我新建一個(gè)控制臺的程序,新建一個(gè)類Student
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; namespace JsonSerializerAndDeSerializer { [DataContract] public class Student { [DataMember] public int ID { get; set; } [DataMember] public string Name { get; set; } [DataMember] public int Age { get; set; } [DataMember] public string Sex { get; set; } } }
注意:上面的Student實(shí)體中的契約 [DataMember],[DataContract],是使用DataContractJsonSerializer
序列化和反序列化必須要加的,對于其他兩種方式不必加,也可以的。
我們程序的代碼:
要先引用程序集,在引入這個(gè)命名空間
//---------------------------------------------------------------------------------------------- //使用DataContractJsonSerializer方式需要引入的命名空間,在System.Runtime.Serialization.dll.中 using System.Runtime.Serialization.Json; //--------------------------------------------------------------------------------------------
#region 1.DataContractJsonSerializer方式序列化和反序列化 Student stu = new Student() { ID = 1, Name = "曹操", Sex = "男", Age = 1000 }; //序列化 DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Student)); MemoryStream msObj = new MemoryStream(); //將序列化之后的Json格式數(shù)據(jù)寫入流中 js.WriteObject(msObj, stu); msObj.Position = 0; //從0這個(gè)位置開始讀取流中的數(shù)據(jù) StreamReader sr = new StreamReader(msObj, Encoding.UTF8); string json = sr.ReadToEnd(); sr.Close(); msObj.Close(); Console.WriteLine(json); //反序列化 string toDes = json; //string to = "{\"ID\":\"1\",\"Name\":\"曹操\",\"Sex\":\"男\(zhòng)",\"Age\":\"1230\"}"; using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(toDes))) { DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(Student)); Student model = (Student)deseralizer.ReadObject(ms);// //反序列化ReadObject Console.WriteLine("ID=" + model.ID); Console.WriteLine("Name=" + model.Name); Console.WriteLine("Age=" + model.Age); Console.WriteLine("Sex=" + model.Sex); } Console.ReadKey(); #endregion
運(yùn)行之后結(jié)果是:
再看看使用JavaScriptJsonSerializer的情況:
JavaScriptSerializer is a class which helps to serialize and deserialize JSON. It is present in namespace System.Web.Script.Serialization which is available in assembly System.Web.Extensions.dll. To serialize a .Net object to JSON string use Serialize method. It's possible to deserialize JSON string to .Net object using Deserialize<T> or DeserializeObject methods. Let's see how to implement serialization and deserialization using JavaScriptSerializer.
這里要先引用
//----------------------------------------------------------------------------------------- //使用JavaScriptSerializer方式需要引入的命名空間,這個(gè)在程序集System.Web.Extensions.dll.中 using System.Web.Script.Serialization; //----------------------------------------------------------------------------------------
#region 2.JavaScriptSerializer方式實(shí)現(xiàn)序列化和反序列化 Student stu = new Student() { ID = 1, Name = "關(guān)羽", 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("動(dòng)態(tài)的反序列化,ID={0},Name={1},Age={2},Sex={3}", modelDy["ID"], modelDy["Name"], modelDy["Age"], modelDy["Sex"]);//這里要使用索引取值,不能使用對象.屬性 Console.WriteLine(messageDy); Console.ReadKey(); #endregion
結(jié)果是:
最后看看使用JSON.NET的情況,引入類庫:
下面的英文,看不懂可略過。。。
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【內(nèi)嵌】 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
運(yùn)行之后,結(jié)果是:
總結(jié)
最后還是盡量使用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.
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
相關(guān)文章
C#中的隨機(jī)數(shù)函數(shù)Random()
這篇文章介紹了C#生成隨機(jī)數(shù)的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-05-05C#事件中的兩個(gè)參數(shù)詳解(object sender,EventArgs e)
這篇文章主要介紹了C#事件中的兩個(gè)參數(shù)詳解(object sender,EventArgs e),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09C#實(shí)現(xiàn)動(dòng)態(tài)創(chuàng)建接口并調(diào)用的實(shí)例
這篇文章介紹了C#實(shí)現(xiàn)動(dòng)態(tài)創(chuàng)建接口并調(diào)用,文中通過實(shí)例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-11-11javascript函數(shù)中執(zhí)行c#函數(shù)的方法
這篇文章主要介紹了javascript和c#函數(shù)和變量互相調(diào)用的方法,大家參考使用吧2014-01-01