Xml与二进制的序列化与反序列化

该博客介绍了如何在Unity中使用C#进行XML和二进制序列化及反序列化操作。作者创建了一个名为TestSerilize的类,并展示了如何设置其属性,然后将其序列化为XML文件和二进制文件。此外,还提供了反序列化方法以从文件中恢复对象。测试结果显示XML序列化成功,生成了包含ID、名称和整数列表的XML结构。
摘要由CSDN通过智能技术生成
  1. 创建测试类
using System;
using System.Collections.Generic;
using System.Xml.Serialization;


[Serializable]
public class TestSerilize
{
   [XmlAttribute("Id")]
   public int Id { get; set;}
   [XmlAttribute("Name")]
   public string Name { get; set;}
   [XmlElement("List")]
   public List<int> List { get; set;}
}

  1. 对Xml和对象进行操作
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml.Serialization;
using UnityEngine;

public class ResoucesTest : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        // SerilizeTest();
        BinarySerTest();
    }

    #region Xml

    private void SerilizeTest()
    {
        TestSerilize testSerilize = new TestSerilize();
        testSerilize.Id = 1;
        testSerilize.Name = "ceshi";
        testSerilize.List = new List<int>();
        testSerilize.List.Add(1);
        testSerilize.List.Add(2);
        testSerilize.List.Add(3);
        XmlSerilize(testSerilize);
    }

    /// <summary>
    /// 类对象系列化成Xml
    /// </summary>
    /// <param name="testSerilize"></param>
    private void XmlSerilize(TestSerilize testSerilize)
    {
        FileStream fileStream = new FileStream(Application.dataPath + "/test.xml", FileMode.Create,
            FileAccess.ReadWrite, FileShare.ReadWrite);
        StreamWriter sw = new StreamWriter(fileStream, Encoding.UTF8);
        XmlSerializer xml = new XmlSerializer(testSerilize.GetType());
        xml.Serialize(sw, testSerilize);
        sw.Close();
        fileStream.Close();
    }

    /// <summary>
    /// Xml反序列化成类对象
    /// </summary>
    /// <returns></returns>
    private TestSerilize XmlDeSerilize()
    {
        FileStream fs = new FileStream(Application.dataPath+"/test.xml",FileMode.Open,FileAccess.ReadWrite,FileShare.ReadWrite);
        XmlSerializer xs = new XmlSerializer(typeof(TestSerilize));
        TestSerilize testSerilize = (TestSerilize) xs.Deserialize(fs);
        fs.Close();
        return testSerilize;
    }

    #endregion

    #region Binary

    private void BinarySerTest()
    {
        TestSerilize testSerilize = new TestSerilize();
        testSerilize.Id = 5;
        testSerilize.Name = "二进制测试";
        testSerilize.List = new List<int>();
        testSerilize.List.Add(10);
        testSerilize.List.Add(18);
        BinarySerilize(testSerilize);
    }

    private void BinarySerilize(TestSerilize testSerilize)
    {
        FileStream fs = new FileStream(Application.dataPath+"/test.bytes",FileMode.Create,FileAccess.ReadWrite,FileShare.ReadWrite);
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(fs,testSerilize);
        fs.Close();
    }

    private TestSerilize BinaryDeserilize()
    {
        TextAsset textAsset = UnityEditor.AssetDatabase.LoadAssetAtPath<TextAsset>("Assets/test.bytes");
        MemoryStream stream = new MemoryStream(textAsset.bytes);
        BinaryFormatter bf = new BinaryFormatter();
        TestSerilize testSerilize = (TestSerilize) bf.Deserialize(stream);
        stream.Close();
        return testSerilize;
    }
    #endregion
}
  1. 测试结果
<?xml version="1.0" encoding="utf-8"?>
<TestSerilize xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Id="1" Name="ceshi">
  <List>1</List>
  <List>2</List>
  <List>3</List>
</TestSerilize>
public static byte[] Serialize<T>(T msg)  {
            byte[] data = null;
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            try {
                bf.Serialize(ms, msg);
                ms.Seek(0, SeekOrigin.Begin);
                data = ms.ToArray();
            }
            catch(SerializationException e) {
                Error("Faild to serialize.Reson:{0}", e.Message);
            }
            finally {
                ms.Close();
            }
            return data;
        }
        public static T DeSerialize<T>(byte[] bytes)  {
            T msg = null;
            MemoryStream ms = new MemoryStream(bytes);
            BinaryFormatter bf = new BinaryFormatter();
            try {
                msg = (T)bf.Deserialize(ms);
            }
            catch(SerializationException e) {
                Error("Faild to deserialize.Reson:{0} bytesLen:{1}.", e.Message, bytes.Length);
            }
            finally {
                ms.Close();
            }
            return msg;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值