Hello, I’m using an asset save system and it works, however I’m trying to mess with it and things start to go wrong. Right now I’m trying to switch from BinaryFormatter to Json.
As I understand the base of the system is a Dictionary which stores pretty much everything; here’s how a new Save File is created:
public static void SaveNew()
SaveablePrefabs.UpdateTable(); //not sure it matters for the current issue
Dictionary<string, object> state = new();
SaveState(state);
SaveFile(state);
here’s SaveFIle:
static void SaveFile(object state)
{
//this is old BF method (which works), ive commented it out
//using (var stream = File.Open(FullSavePath, FileMode.Create))
//{
// var formatter = new BinaryFormatter();
// formatter.Serialize(stream, state);
//}
//here's what im trying to do
//using Newtonsoft Json 3.2.1 to convert
var saveDict = JsonConvert.SerializeObject(state);
File.WriteAllText(FullSavePath, saveDict);
}
deseriazing is basically this:
string saveDict = File.ReadAllText(FullSavePath);
Dictionary<string, object> newDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(saveDict);
It saves fine, but on loading it gives ‘Specified cast is not valid’ on this line:
var stateDictionary = (Dictionary<string, object>)state;
After like 3 days of thinking and debugging it looks like the value of the dict (which is Object) gets changed during serialization process and can’t be used anymore. So do i need to serialize it as well? If so how can it be done? I may be wrong of course, since I have little experience with dictionaries and serialization in general.
So how to properly serialize this kind of dictionary with jason? I’m open to all kinds of suggestions (maybe a different formatting method), though I’m not sure if it’s possible to change the dictonary itself, since it’s gonna break pretty much the whole system.