I am using the Json namespace provided by .NET, not the Newtonsoft one. I have a piece of code:
string text;
text = File.ReadAllText(EntityDirectory + @"\Json\AbilityTemplates.json");
foreach (AbilityTemplate template in JsonSerializer.Deserialize<List<AbilityTemplate>>(text)) {
loaderInterface.AddAbilityTemplate(template);
}
When the code run to the JsonSerializer.Deserialize, an execption was thrown.
System.Text.Json.JsonException: 'The JSON value could not be converted to System.Collections.Generic.List`1[Enigma.Game.AbilityTemplate]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.'
This is the Json text that I have:
{
{
"ID": "StandardShot",
"Price": "10",
"Size": "1",
"Rarity": "Common",
"AbilityEffectFactory": "StandardShotEffectFactory"
},
{
"ID": "SelfDestructSingleDamage",
"Price": "0",
"Size": "0",
"Rarity": "NotForPlayer",
"AbilityEffectFactory": "SelfDestructSingleDamageEffectFactory"
}
}
I wrote a constructor with JsonConstructor Attribute, but seems like it didn't work:
public AbilityTemplate(string id, int price, int size, Rarity rarity, AbilityEffectFactory abilityEffectFactory) {
Id = id;
Price = price;
Size = size;
Rarity = rarity;
AbilityEffectFactory = abilityEffectFactory;
}
[JsonConstructor]
public AbilityTemplate(string id, int price, int size, Rarity rarity, string abilityEffectFactory) : this(id, price, size, rarity, AbilityEffectFactory.Dictionary[abilityEffectFactory]) { }
Rarity is an enum type.
————————Edit——————————
I change the brackets from {} to [],and also made the fields in json text exactly match the parameters name, but it still didn't work. This is my new Json text:
[
{
"id": "StandardShot",
"price": "10",
"size": "1",
"rarity": "Common",
"abilityEffectFactory": "StandardShotEffectFactory"
},
{
"id": "SelfDestructSingleDamage",
"price": "0",
"size": "0",
"rarity": "NotForPlayer",
"abilityEffectFactory": "SelfDestructSingleDamageEffectFactory"
}
]
System.InvalidOperationException: 'Each parameter in the deserialization constructor on type 'Enigma.Game.AbilityTemplate' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive.'