[英]c# Deserialize derived class in a JSON file
我正在開發一個游戲機應用程序,該應用程序反序列化 JSON 個文件,代表玩家必須處理的不同遭遇。
我有一種名為“LootEvent”的特定類型的遭遇,其中包含玩家可以獲得的物品。 這是代碼:
這是 LootEvent class 及其屬性
public class LootEvent
{
public string Name;
public string Fluff;
public Item Item;
public List<LootAction> Actions;
}
下面是一個 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}]
}
如您所見,沒有“Item”字段,這是因為“Weapon”字段是 Item 的派生 class:
這是項目 class:
public class Item
{
public string Name;
public int Bonus;
}
這是武器 class:
public class Weapon : Item
{
}
我還有其他從 Item 派生的 class,它們與“武器”class 的樣式相同,例如“盔甲”或“葯水”class。
現在我使用這種方法來轉換我的 json 文件:
//the "json" variable is a string that contains all of the JSON file text
JsonConvert.DeserializeObject<LootEvent>(json);
因此,當我將 JSON 文件轉換為 LootEvent 時,所有字段都傳遞到 LootEvent object,但 Item 屬性除外,因為 JSON 中沒有 Item 字段,而是武器或盔甲或任何派生的 class 項目。
我的問題是:如何反序列化這些派生的 class?
使用這個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.