美文网首页
ProtoBuf序列化与反序列化

ProtoBuf序列化与反序列化

作者: 醉酒青牛_fa4e | 来源:发表于2018-03-28 00:35 被阅读0次

//对于要序列化的类进行配置
//步骤:
//1、引用ProtoBuf命名空间
//2、给类添加标签[ProtoContract]
//3、给属性添加标签[ProtoMember(数字)],数字为属性的编号,从1开始,没有0.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ProtoBuf;

[ProtoContract]
public class Person {
/// <summary>
/// protobuf从1开始编号,没有0
/// </summary>
[ProtoMember(1)]
public string persoName;

[ProtoMember(2)]
public int presonAge;

}

//序列化与反序列化
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ProtoBuf;
using System.IO;

public class Demo : MonoBehaviour {

Person p;
byte[] buffer;
void Start () {
    p = new Person();
    p.persoName = "Tom";
    p.presonAge = 18;
}

void OnGUI () {
    if (GUILayout.Button("序列化")){
        //创建内存流
        using(MemoryStream ms=new MemoryStream())//使用using时,函数结束即释放此内存,不需要gc
        {
            //将对象序列化到内存流中
            Serializer.Serialize<Person>(ms, p);
            //实例化buffer数组
            buffer = new byte[ms.Length];               
            //获取内存流中的数据。获取时不要用Stream.GetBuffer,因为出现此问题的原因是,
            //在使用 byte[] buffer= stream.GetBuffer()时,返回的byte[]不是完全的有效数据,
            //而是在末尾有填充很多0的字节数组,因而在ProtoBuf.Serializer.Serialize时或ProtoBuf.Serializer.Deserialize时会抛出异常。
            //正确的做法是,不使用stream.GetBuffer(),而使用stream.ToArray()代替,或者使用stream.GetBuffer(),
            //但是在生成stream时,使用stream.Length(这个是实际有效字节长度),而不是buffer.Length(这个是填充0的总字节长度)。 
            buffer = ms.ToArray();
        }
    }

    if (GUILayout.Button("反序列化"))
    {
        using (MemoryStream ms = new MemoryStream(buffer))
        {
            //ms.Position = 0;
            //反序列化
            Person newP= Serializer.Deserialize<Person>(ms);

            Debug.Log(newP.persoName+"+"+newP.presonAge);
        }
    }
}

}

相关文章

网友评论

      本文标题:ProtoBuf序列化与反序列化

      本文链接:https://www.haomeiwen.com/subject/vsbecftx.html