這次帶給大家Json怎麼實現序列化與反序列化(附代碼),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物件表示方法】,它是一個輕量級的資料交換格式,我們可以很簡單的來讀取和寫它,並且它很容易被電腦轉換和生成,它是完全獨立於語言的。
Json支援下面兩種資料結構:
#鍵值對的集合--各種不同的程式語言,都支援這種資料結構;
有序的列表類型值的集合--這其中包含數組,集合,向量,或序列,等等。
Json有以下幾種表現形式
1.物件
#一個沒有順序的「鍵/值」,一個物件以花括號「{」開始,並以花括號"}"結束,在每一個「鍵」的後面,有一個冒號,並且使用逗號來分隔多個鍵值對。
例如:
var user = {"name":"Manas","gender":"Male","birthday":"1987-8-8"}
2.陣列
#設定值的順序,一個陣列以中括號"["開始,並以中括號" ]"結束,並且所有的值使用逗號分隔例如:var userlist = [{"user":{"name":"Manas","gender":"Male","birthday":"1987-8-8"}}, {"user":{"name":"Mohapatra","Male":"Female","birthday":"1987-7-7"}}]#3.字串任意數量的Unicode字符,使用引號做標記,並使用反斜線來分隔。
var userlist = "{\"ID\":1,\"Name\":\"Manas\",\"Address\":\"India\"}"
好了,介紹完JSON,現在說正題。
JavaScriptSerializer
類別使用DataContractJsonSerializer類別
我們先來看看使用DataContractJsonSerializer的情況
DataContractJsonSerializer類別幫助我們序列化和反序列化Json,他在組件 System.Runtime.Serialization.dll下的
System.Runtime.Serialization.Json命名空間
裡。首先,這裡,我新建一個控制台的程序,新建一個類別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; }
}
}
DataContractJsonSerializer序列化和反序列化必須要加的,對於其他兩種方式不必加,也可以的。
###我們程式的程式碼:#########要先引用組件,在引入這個命名空間###//---------------------------------------------------------------------------------------------- //使用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格式数据写入流中 js.WriteObject(msObj, stu); msObj.Position = 0; //从0这个位置开始读取流中的数据 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\":\"男\",\"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######運行之後結果是:# ########### ############再看看###使用JavaScript###JsonSerializer的情況:############ 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 objuse to Jerial string. It's possible to deserialize JSON string to .Net object using Deserialize
//----------------------------------------------------------------------------------------- //使用JavaScriptSerializer方式需要引入的命名空间,这个在程序集System.Web.Extensions.dll.中 using System.Web.Script.Serialization; //----------------------------------------------------------------------------------------
#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
结果是:
最后看看使用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【内嵌】 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
运行之后,结果是:
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
以上是Json怎麼實現序列化與反序列化(附程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!