C#中的XML序列化和Json序列化,普通数组转字节数组

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";
        }

    }
}

读者可以从中这几个例子中直观的看出各种序列化和二进制转换的区别,也可以自己调试一下
本案例代码下载地址
https://download.csdn.net/download/github_34777264/10469531

猜你喜欢

转载自blog.csdn.net/github_34777264/article/details/80629038