Reputation: 351
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;
}
Upvotes: 3
Views: 4434
Reputation: 29
If you try adding the code solution and think it didn't help, you MUST uninstall the app from your device.
That's because of the data corruption on the file you attempt to create in the first place.
I had the issue, and that solve the problem.
Upvotes: 0
Reputation: 886
I got this same error but it was due to a corrupt file created by the binary formatter serialization method. In my case, I observed that I had a JIT compilation error when serializing. This was somehow creating a file but with no correct data in it so whenever I tried to deserialized I got thie "unexpected binary element : 255" message.
Please, read this if you also find this behaviour on your serialization method.
It all reduces to use this line in the monobehavior using the formatter:
// 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");
For a further explanation of why are you needing this please visit the referenced link.
Upvotes: 0
Reputation: 351
After some sleep and some more googling I found that I should be using the FileStream
class instead of StreamReader
and StreamWriter
. Changing this makes it work.
Upvotes: 1