private static string getJsonByObject(Object obj) { //实例化DataContractJsonSerializer对象,需要待序列化的对象类型 DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); //实例化一个内存流,用于存放序列化后的数据 MemoryStream stream = new MemoryStream(); //使用WriteObject序列化对象 serializer.WriteObject(stream, obj); //写入内存流中 byte[] dataBytes = new byte[stream.Length]; stream.Position = 0; stream.Read(dataBytes, 0, (int) stream.Length); //通过UTF8格式转换为字符串 return Encoding.UTF8.GetString(dataBytes); }
-------------------------------------------------------
在.NET编程中,经常面向对象处理完以后要转换成另一种格式传输或存储,这种将对象转向其他数据格式的过程,即序列化(Serialization)。
当两个进程在进行远程通信时,彼此可以发送各种类型的数据。无论是何种类型的数据,都会以二进制序列的形式在网络上传送。发送方需要把这个对象转换为字节序列,才能在网络上传送;接收方则需要把字节序列再恢复为对象。
把对象转换为字节序列的过程称为对象的序列化。
把字节序列恢复为对象的过程称为对象的反序列化。
说的再直接点,序列化的目的就是为了跨进程传递格式化数据
1. 什么是序列化和反序列化?
序列化(Serialization):序列化是将对象状态转换为可保持或传输的格式的过程。
反序列化(Deserialization) :与序列化相对的是反序列化,它将流转换为对象。这两个过程结合起来,可以轻松地存储和传输数据。
在序列化期间,对象将其当前状态写入到临时或永久性存储区(存入文件中)。以后,可以通过从存储区中读取或反序列化对象的状态,重新创建该对象。以此达到面向对象中的永续生存。(这句话的意思也就是,用二进制的序列化的形式,将"资源"保存到磁盘文件里,磁盘不损坏,则资源就存在)
注意一下:[Serializable]标识
Serializable属性用来明确表示该类可以被序列化。
同样的,我们可以用NonSerializable属性用来明确表示类不能被序列化。
----------------------------------------------------------------------------------------------------------------------------------
function getForm() { var form = new mini.Form("#form1"); var data = form.getData(true, false); var s = mini.encode(data); alert(s); //form.setIsValid(false); } function submitForm() { //提交表单数据 var form = new mini.Form("#form1"); var data = form.getData(); //获取表单多个控件的数据 var json = mini.encode(data); //序列化成JSON ----->>> "ID":"qwe7sf-sd77f","name":"lisi" $.ajax({ url: "../data/FormService.aspx?method=SaveData", type: "post", data: { submitData: json }, success: function(text) { alert("提交成功,返回结果:" + text); } }); }
function loadForm() { //加载表单数据 var form = new mini.Form("#form1"); $.ajax({ url: "../data/FormService.aspx?method=LoadData", type: "post", success: function(text) { var data = mini.decode(text); //反序列化成对象----->ID:"34f-ererw324',name:"lisi" form.setData(data); //设置多个控件数据 } }); }
=========================第一种=====================================================
namespace 序列化Itcast { public class Program { public static void Main(string[] args) { // Person p = new Person(); // p.Name = "朱凯彬"; // p.Age = 12; // p.Email = "qwe@qq.com"; ////二进制序列化就是把对象变成流的过程,变成byte[] ////变成流以后可以从网上下载也可以写进磁盘(FileStream)中 ////1.创建二进制 // BinaryFormatter bf = new BinaryFormatter(); ////2.创建流,就是为了写入磁盘 // //3. [Serializable] // using (FileStream fs = new FileStream(@"F:桌面考过来的C#·小程序123.txt", FileMode.Create)) // { // bf.Serialize(fs, p); // } // Console.WriteLine(bf); // Console.WriteLine("序列完毕"); // //Console.ReadKey(); // #region Json和XML // ////XML序列化 // XmlSerializer xml = new XmlSerializer(typeof(Person)); // using (FileStream fs = new FileStream("Person.xml", FileMode.Create))//因为xml要保存到磁盘上,所以写一个文件流,磁盘上的某一个文件 // { // xml.Serialize(fs, p); // } // Console.WriteLine("ok"); // //Console.ReadKey(); // // <?xml version="1.0"?> // //<Person xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> // // <Name>朱凯彬</Name> // // <Age>12</Age> // // <Email>qwe@qq.com</Email> // //</Person> // //Json序列号 // JavaScriptSerializer js = new JavaScriptSerializer(); // string msg = js.Serialize(p); // //{"Name":"朱凯彬","Age":12,"Email":"qwe@qq.com"} // //转成了字符串形式,对象以这种字符串的格式进行存储,按照一定得格式进行解析,就能还原对象 // Console.WriteLine(msg); // Console.ReadKey(); // #endregion [Serializable] public class Person { public string Name{ set; get;} public int Age{ set; get;} public string Email{ set; get;} }
----------------------------------------第二种----------------------------------------------------------------------------------------------------------
[Serializable] class MartialArtsMaster { public int Id { get;set; } public string Name {get; set;} public int Age {get;set;} public string Menpai{get;set;} public string Kungfu{get;set;} public int Level{get;set;} } /// <summary> /// 二进制序列化和反序列化类 /// </summary> public class Serializer { /// <summary> /// 使用二进制序列化对象。 /// </summary> /// <param name="value"></param> /// <returns></returns> public static byte[] SerializeBytes(object value) { if(value == null) return null; var stream = new MemoryStream(); new BinaryFormatter().Serialize(stream, value); var bytes = stream.ToArray(); return bytes; } /// <summary> /// 使用二进制反序列化对象。 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static object DeserializeBytes(byte[] bytes) { if(bytes == null) return null; var stream = new MemoryStream(bytes); var result = new BinaryFormatter().Deserialize(stream); return result; } } } } //初始化武林高手 var master = new List < MartialArtsMaster > () { new MartialArtsMaster() { Id = 1, Name = "黄蓉", Age = 18, Menpai = "丐帮", Kungfu = "打狗棒法", Level = 9 }, new MartialArtsMaster() { Id = 2, Name = "洪七公", Age = 70, Menpai = "丐帮", Kungfu = "打狗棒法", Level = 10}, new MartialArtsMaster() { Id = 3, Name = "郭靖", Age = 22, Menpai = "丐帮", Kungfu = "降龙十八掌", Level = 10}, new MartialArtsMaster() { Id = 4, Name = "任我行", Age = 50, Menpai = "明教", Kungfu = "葵花宝典", Level = 1}, new MartialArtsMaster() { Id = 5, Name = "东方不败", Age = 35, Menpai = "明教", Kungfu = "葵花宝典", Level = 10}, new MartialArtsMaster() { Id = 6, Name = "林平之", Age = 23, Menpai = "华山", Kungfu = "葵花宝典", Level = 7}, new MartialArtsMaster() { Id = 7, Name = "岳不群", Age = 50, Menpai = "华山", Kungfu = "葵花宝典", Level = 8} }; //文件流写入 //using (FileStream fs = new FileStream(@"F:桌面考过来的C#·小程序123.txt", FileMode.Append)) //{ // var myByte = Serializer.SerializeBytes(master); // fs.Write(myByte, 0, myByte.Length); // fs.Close(); //}; //文件流读取 using(FileStream fsRead = new FileStream(@"F:桌面考过来的C#·小程序123.txt", FileMode.Open)) { int fsLen = (int) fsRead.Length; byte[] heByte = new byte[fsLen]; int r = fsRead.Read(heByte, 0, heByte.Length); var myObj = Serializer.DeserializeBytes(heByte) as List < MartialArtsMaster > ; Console.WriteLine("编号---姓名---年龄---门派---武功---等级"); myObj.ForEach(m => Console.WriteLine(m.Id + "---" + m.Name + "---" + m.Age + "---" + m.Menpai + "---" + m.Kungfu + "---" + m.Level)); } Console.ReadKey(); }
==================================第三种===========================================
//序列化操作 JavaScriptSerializer jss = new JavaScriptSerializer(); var json = new { name = "fxhl", age = 23 }; string str = jss.Serialize(json); Console.WriteLine(str); //{"name":"fxhl","age":23} //反序列化操作 Person person = jss.Deserialize < Person > (str); Console.WriteLine(person.name); //fxhl Console.ReadKey(); [Serializable] public class Person { public string name { get; set; } public int age { get; set; } }
-----------------------------------第四种------------------------------------------------------------
Personnel personnel = new Personnel(); personnel.Id = 1; personnel.Name = "小白"; JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); //执行序列化 string r1 = jsonSerializer.Serialize(personnel); Console.WriteLine(r1); //{"Id":1,"Name":"小白"} //执行反序列化 Personnel _Personnel = jsonSerializer.Deserialize < Personnel > (r1); Console.WriteLine(_Personnel + "456"); //序列化Itcast.Program+Personnel456 [Serializable] public class Personnel { public int Id { get; set; } public string Name { get; set; } }
---------------------第五种--------------------------------------------------------
引用Json.Net
//序列化操作 var json = new { user = new { name = "fxhl", age = 23 } }; string jsonData = JsonConvert.SerializeObject(json); Console.WriteLine(jsonData); //{"user":{"name":"fxhl","age":23}} //反序列化操作方法一 Person p1 = JsonConvert.DeserializeObject < Person > (jsonData); Console.WriteLine(p1.user.name); //fxhl //反序列化操作方法二 string json2 = "[{"user":{"name":"fxhl","age":23}}]"; List < Person > listp2 = JsonConvert.DeserializeObject < List < Person >> (json2); Console.WriteLine(listp2[0].user.name); //fxhl Console.ReadKey(); public class Person { public Person user { get; set; } public string name { get; set; } public int age { get; set; } }