简体   繁体   English

c# 在 JSON 文件中反序列化派生的 class

[英]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.我正在开发一个游戏机应用程序,该应用程序反序列化 JSON 个文件,代表玩家必须处理的不同遭遇。

I have a particular type of encounter named "LootEvent" which contains an Item that the player can gain.我有一种名为“LootEvent”的特定类型的遭遇,其中包含玩家可以获得的物品。 Here's the code:这是代码:

Here's the LootEvent class with its attributes这是 LootEvent class 及其属性

    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:下面是一个 JSON 文件的示例,我想将其转换为 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:如您所见,没有“Item”字段,这是因为“Weapon”字段是 Item 的派生 class:

Here's the Item class:这是项目 class:

    public class Item
    {
        public string Name;
        public int Bonus;
    }

And here's the Weapon class:这是武器 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.我还有其他从 Item 派生的 class,它们与“武器”class 的样式相同,例如“盔甲”或“药水”class。

Now I use this method to convert my json file:现在我使用这种方法来转换我的 json 文件:

//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.因此,当我将 JSON 文件转换为 LootEvent 时,所有字段都传递到 LootEvent object,但 Item 属性除外,因为 JSON 中没有 Item 字段,而是武器或盔甲或任何派生的 class 项目。

My question is: How can I deserialize these derived class?我的问题是:如何反序列化这些派生的 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.使用这个JsonKnownTypes ,它的使用方式非常相似,它只是将鉴别器添加到 json。但是您还需要将其用于序列化,或者如果它是外部的,您需要找到一些属性来定义 class 序列化器需要使用的内容。

[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
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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