C#中的XML序列化和Json序列化,普通陣列轉位元組陣列
阿新 • • 發佈:2019-01-23
C#在於其他語言進行資料通訊時,直接傳遞的時二進位制的位元組碼,而一個要傳遞的物件的二進位制位元組碼在C#中有很多表示方法。其中直接轉換為Byte陣列和序列化未byte陣列,還有xml序列化,json序列化最未常用,下面簡單舉例介紹一下這幾種方法。
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json;
namespace Test1
{
class Program
{
static void Main(string [] args)
{
short i = 1024;
short[] arrI = new short[] { 2, 4, 8, 16 };
#region 位元組轉換測試程式
byte[] intBuff = BitConverter.GetBytes(i);
byte[] intArrBuff = new byte[arrI.Length * sizeof(short)];
Buffer.BlockCopy(arrI, 0, intArrBuff, 0 , intArrBuff.Length);
short rei = BitConverter.ToInt16(intBuff, 0);
short[] reArrI = new short[intArrBuff.Length / sizeof(short)];
Buffer.BlockCopy(intArrBuff, 0, reArrI, 0, intArrBuff.Length);
Console.WriteLine(rei);
#endregion
#region 陣列的序列化
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, arrI);
byte[] newArray = new byte[ms.Length];
ms.Position = 0;
ms.Read(newArray, 0, newArray.Length);
ms.Close();
// 反序列化
MemoryStream memo = new MemoryStream(newArray);
bf.Deserialize(memo);
#endregion
#region 類的序列化
Person man = new Person();
man.name = "David";
man.sex = "male";
man.age = 21;
//序列化
MemoryStream ms01 = new MemoryStream();
BinaryFormatter bf01 = new BinaryFormatter();
bf01.Serialize(ms01, man);
byte[] arr01 = new byte[ms01.Length];
ms01.Position = 0;
ms01.Read(arr01, 0, arr01.Length);
ms01.Close();
//解序列化
MemoryStream ms001 = new MemoryStream(arr01);
BinaryFormatter bf001 = new BinaryFormatter();
Person newMan = (Person)bf001.Deserialize(ms001);
#endregion
#region 類的json序列化
Console.WriteLine(man.say());
string srMan = JsonConvert.SerializeObject(man);
Console.WriteLine(srMan);
//json反序列化
Person newaMan = JsonConvert.DeserializeObject<Person>(srMan);
newaMan.say(); //序列化再反序列化之後man變啞了
#endregion
Console.ReadKey();
}
}
}
用到的Person類的定義是
using System;
namespace Test1
{
[Serializable]
class Person
{
public string name;
public string sex;
public int age;
public string say()
{
return "hello,world";
}
}
}