0

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?
Ian
  • 30,182
  • 19
  • 69
  • 107
  • What language is this? – user207421 Sep 11 '15 at 10:22
  • 1
    Most JSON serializers in .Net have mechanisms for handling polymorphic types. Json.NET has [`TypeNameHandling = TypeNameHandling.Auto`](http://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm). `DataContractJsonSerializer` has [type hints](https://msdn.microsoft.com/en-us/library/bb412170%28v=vs.110%29.aspx), as does [`JavaScriptSerializer`](https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer%28v=vs.110%29.aspx). What serializer are you using? – dbc Sep 11 '15 at 18:12
  • I am using Newtonsoft.Json – Lorry Laurence mcLarry Sep 11 '15 at 23:08
  • 2
    Perhaps http://stackoverflow.com/questions/22080387/json-net-does-not-serialize-properties-from-derived-class will be of some use. Or http://stackoverflow.com/questions/8513042/json-net-serialize-deserialize-derived-types. Or perhaps https://christianarg.wordpress.com/2012/11/06/serializing-and-deserializing-inherited-types-with-json-anything-you-want/. A few minutes with your favorite search engine looking for *serialize derived class json.net* should lead you to the answer. – Jim Mischel Sep 12 '15 at 00:00
  • See also [Deserializing polymorphic json classes without type information using json.net](http://stackoverflow.com/q/19307752/10263) – Brian Rogers Sep 13 '15 at 16:17

0 Answers0