数据的存储和传输往往都是以字节码的形式进行,那么,在Unity中,如何把格式化的列表转成字节码,然后又把字节码恢复成原本来格式化数据呢?
注意:用 System.Runtime.Serialization.Formatters.Binary 进行系列化和反系列化的时候,反系列化时会报错:提示找不到某某版本的程序集。 比如:Unity的exe作为客户端,它把信息传送到服务器[winForm]上,当服务器反系列化的时候,因为程序集的版本不一致,导致报错。更通用的做法就是把对象系列化成Json 大致流程如下:Object -> Json -> UTF8 -> byte[] -> 网络传输 byte[] -> UTF8 -> Json -> Object
一、【格式化数据】的【系列化】和【反系列化】
二、【系列化】和【反系列化】的关键要点
using System.Runtime.Serialization.Formatters.Binary;
BinaryFormatter.Serialize(stream对象,数据对象);
BinaryFormatter.Deserialize(stream对象);
- 4、其它知识:内存流对象MemoryStream与字节数组byte[]的转换
List<byte> buffer = new List<byte>();
stream to byte[]
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, sendData);
buffer.AddRange(stream.ToArray());
byte[] to stream
MemoryStream stream2 = new MemoryStream(buffer.ToArray());
三、Unity中的服用方法
四、demo代码
- 测试环境 win10 + unity2020.3 in UnityEditor
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System;
[Serializable]
public class SendData
{
[SerializeField]
public string resproCode;
[SerializeField]
public int status;
[SerializeField]
public int score;
[SerializeField]
public long startTime;
[SerializeField]
public long endTime;
[SerializeField]
public List<StepData> steps = new List<StepData>();
}
[Serializable]
public class StepData
{
[SerializeField] public int seq;
[SerializeField] public string title;
[SerializeField] public long startTime;
[SerializeField] public long endTime;
[SerializeField] public int expectTime;
[SerializeField] public int maxScore;
[SerializeField] public int score;
[SerializeField] public int repeatCount;
[SerializeField] public string evaluation;
[SerializeField] public string scoringModel;
[SerializeField] public string remarks;
}
public class Deserilize : MonoBehaviour
{
public Button btnTest;
[Header("【1】要系列化的对象")]
public SendData sendData;
[Header("【2】用来传输或者存储的字节码")]
public byte[] serBytes;
[Header("【3】反系列化后恢复的对象")]
public SendData deSendData;
void Start()
{
btnTest.onClick.AddListener(() =>
{
List<byte> buffer = new List<byte>();
buffer.AddRange(Serialize(sendData));
serBytes = buffer.ToArray();
var res = DeSerialize<SendData>(serBytes);
Debug.Log("总分数:" + res.resproCode);
Debug.Log("步骤数量:" + res.steps.Count);
deSendData = res;
});
}
public static byte[] Serialize<T>(T dataToSerialize)
{
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, dataToSerialize);
return stream.ToArray();
}
public static T DeSerialize<T>(byte[] bytesAry)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream2 = new MemoryStream(bytesAry);
return (T)formatter.Deserialize(stream2);
}
}
|