I need some help with serializing a nested datastructure using Json.Net for Unity.
I have an interface called ISaveable:
public interface ISaveable
{
object Save();
void Load(object data);
}
My Inventory for example uses this interface as such:
//InventoryData is decorated with [System.Serializable]
private InventoryData inventoryData;
object Save()
{
return inventoryData;
}
void Load(object data)
{
inventoryData = (InventoryData)data;
}
The class that is passed to JsonConvert looks like this:
[System.Serializable]
public class SaveData
{
public string Name;
public Dictionary<string, object> state;
}
A class responsible for saving and loading then loops over all MonoBehaviours that inherit ISaveable and gets/sets the data.
The object gets serialized properly but when deserializing and passing the data as object
to the inventory I get an error saying the cast is invalid.
I did manage to overcome the issue by setting TypeNameHandling
to All but I started using a custom converter package that doesn’t work with passing custom settings to the serializer.
What would be the correct way of handling such an object with nested data, where the type of the data is unknown during serialization?
Thanks in advance!