3

I am trying to save my custom class using binary serialization in c#. I have the serialization working fine (as far as I can tell, I get no errors) but when I try to deserialize it I get the following error:

SerializationException: Unexpected binary element: 255

Does anybody got ideas as to what could be causing this? I'm using C# with the Unity game engine.

EDIT:

Here's the code, it's inside the class for my editor window.

public static LevelMetaData LoadAllLevels()
{
    string filepath = Path.Combine(Application.dataPath, "Levels/meta.dat");

    BinaryFormatter serializer = new BinaryFormatter();

    if (File.Exists(filepath))
    {
        using (StreamReader sr = new StreamReader(filepath))
        {
            return (LevelMetaData)serializer.Deserialize(sr.BaseStream);
        }
    }
    else
    {
        LevelMetaData temp = new LevelMetaData();

        using (StreamWriter sw = new StreamWriter(filepath))
        {
            serializer.Serialize(sw.BaseStream, temp);
        }
        return temp;
    }
}

EDIT 2:

Here's the LevelMetaData class:

[Serializable]
public class LevelMetaData
{
    public LevelMetaData()
    {
        keys = new List<string>();
        data = new List<LevelController>();
    }

    public LevelController this[string key]
    {
        get
        {
            if (keys.Contains(key))
                return data[keys.IndexOf(key)];
            else
                throw new KeyNotFoundException("Level with key \"" + key + "\"not found.");
        }
    }

    public void Add(string key, LevelController level)
    {
        if (!keys.Contains(key))
        {
            keys.Add(key);
            data.Add(level);
        }
    }

    public bool Contains(string key)
    {
        return keys.Contains(key);
    }

    public List<string> keys;
    public List<LevelController> data;
}
4

3 回答 3

1

经过一番睡眠和更多谷歌搜索后,我发现我应该使用FileStream该类而不是StreamReaderand StreamWriter。改变它使它工作。

于 2013-11-11T10:28:24.410 回答
0

如果您尝试添加代码解决方案并认为它没有帮助,您必须从您的设备上卸载该应用程序。

这是因为您首先尝试创建的文件的数据损坏。

我遇到了问题,这解决了问题。

于 2015-01-28T17:14:42.533 回答
0

我得到了同样的错误,但这是由于二进制格式化程序序列化方法创建的损坏文件。就我而言,我观察到序列化时出现 JIT 编译错误。这以某种方式创建了一个文件,但其中没有正确的数据,所以每当我尝试反序列化时,我都会收到“意外的二进制元素:255”消息。

如果您在序列化方法中也发现此行为,请阅读此内容。

这一切都减少了使用格式化程序在单一行为中使用这一行:

// Forces a different code path in the BinaryFormatter that doesn't rely on run-time code generation (which would break on iOS).
 enter code here`Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");

有关您为什么需要此功能的进一步说明,请访问参考链接

于 2014-10-29T12:35:34.890 回答