I'm using C
# and Newtonsoft.Json
. I am making an RPG
where the characters are saved to disk using Json
. Characters
include an inventory
.
My 'Inventory
' Class:
public class Inventory
{
public Dictionary<EquipmentSlot, Equipment> Equiped = new Dictionary<EquipmentSlot, Equipment>();
public Dictionary<CurrencyType, float> Currency = new Dictionary<CurrencyType, float>();
public Item[] Loot = new Item[LootLimit];
//some extra methods and stuff
}
"Equipment
" is an abstract class
from which "Armour
", "Weapon
" and "Shield
" are derived. "Armour
" is not a non-abstract class
, "Weapon
" is an abstract class
, and Shield
is non-abstract
for the moment because I haven't designed it yet.
The problem is that because the reference to the character's equipment is cast as "Dictionary<EquipmentSlot, Equipment>
", Json
only saves the properties of the "Equipment
" base class
. Then when it de-serializes, it attempts to instantiate "Equipment
" and crashes because "Equipment
" is abstract
.
I can see that this is going to be a massive problem for me because everywhere I have Dictionaries
, Lists
, Arrays
and other data-structures typed as base class, where each member is a derived class
.
- How to make this work?
- Is there a better form of serialisation than Json?
- Or is there a better version to use than Newtonsoft.Json.Dll?
- Do I need to write custom serialisation into my classes? (example?)
- Is there some better solution?