I'm working on a game console application that deserialize JSON files that represent differents encounters the player has to deal with.
I have a particular type of encounter named "LootEvent" which contains an Item that the player can gain. Here's the code:
Here's the LootEvent class with its attributes
public class LootEvent
{
public string Name;
public string Fluff;
public Item Item;
public List<LootAction> Actions;
}
Now here's an example of a JSON file that I want to convert into a LootEvent object:
{
"Name" : "A first Loot",
"Fluff" : "Will you take this item?",
"Weapon" : {"Name": "Iron Dagger", "Bonus": 1 },
"Actions" : [{"Text": "Yes", "HasLoot" : true},
{"Text": "No", "HasLoot" : false}]
}
As you see there is no "Item" field it's because the field "Weapon" is a derived class of Item:
Here's the Item class:
public class Item
{
public string Name;
public int Bonus;
}
And here's the Weapon class:
public class Weapon : Item
{
}
I have other derived class from Item which are in the same style of the "Weapon" class like an "Armor" or "Potion" class.
Now I use this method to convert my json file:
//the "json" variable is a string that contains all of the JSON file text
JsonConvert.DeserializeObject<LootEvent>(json);
So when I convert the JSON File into a LootEvent, all the fields are passed into the LootEvent object except the Item attribute because there's not an Item field in the JSON but a Weapon or Armor or whatever derived class of Item it is.
My question is: How can I deserialize these derived class?