简体   繁体   中英

c# Deserialize derived class in a JSON file

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?

Use this JsonKnownTypes , it's very similar way to use, it just adddiscriminator to json. But you also need to use that for serialization or if it is external you need to find some property to define what class serializator need to use.

[JsonConverter(typeof(JsonKnownTypeConverter<BaseClass>))]
[JsonDiscriminator(Name = "Name")]
[JsonKnownType(typeof(Base), "Some item")]
[JsonKnownType(typeof(Derived), "weapon")]
public class Item
{
    public string Name;
    public int Bonus;
}
public class Weapon : Item
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM