Home > Back-end >  Json Deserializer Returning NUll
Json Deserializer Returning NUll

Time:09-04

Hello I am trying to deserialize a json file. A sample of it is below from the start to the first element:

 {
  "spell": [
    {
      "name": "Affect Normal Fires",
      "school": "Al",
      "verbal": "1",
      "somatic": "1",
      "material": "0",
      "materials": "",
      "range": "5 yds./level",
      "aoe": "10 foot-radius",
      "castingTime": "1",
      "duration": "2 rds./level",
      "save": "None",
      "damage": "",
      "description": "...",
      "level": "1",
      "caster": "Wizard",
      "source": "Players Hand Book page 170",
      "sphere": [],
      "subschools": [ "Elemental Fire", "Alchemy" ]
    },...

I created the class structure for it below:

   public class Spells
   {
       public List<Spell> list_of_spells { get; set;}
   }

   public class Spell 
   {
       public string name { get; set; }
       public string school { get; set;}
       public string verbal { get; set;} 
       public string somatic { get; set;}
       public string material { get; set;}
       public string materials { get; set;}
       public string range { get; set;} 
       public string aoe { get; set;}
       public string castingTime { get; set;}
       public string duration { get; set;}
       public string save { get; set;}
       public string damage { get; set;}
       public string description { get; set;}
       public string level { get; set;}
       public string caster { get; set;}
       public string source { get; set;}
       public List<string> sphere { get; set;}
       public List<string> subschools { get; set; }
   }

Now When I try to Deserialize it by doing this

Spells loadedSpells;
loadedSpells = JsonSerializer.Deserialize<Spells>(File.ReadAllText(@"C:\spellsv2.json"));

loadedSpells.list_of_spells just equals Null

Is there something I'm missing?

CodePudding user response:

fix the class

   public class Spells
   {
       public List<Spell> spell { get; set;}
   }

Spells loadedSpells = JsonSerializer.Deserialize<Spells>(File.ReadAllText(@"C:\spellsv2.json"));

or you can keep your property name

public class Spells
   {   
       [JsonPeropertyName("spell")]
       public List<Spell> list_of_spells { get; set;}
   }

CodePudding user response:

The name of your property in the spells class must be the same name as the root object in the json file in order to be correctly mapped to it.

try changing :

public class Spells
{
   public List<Spell> list_of_spells { get; set;}
}

to :

public class Spells
{
   public List<Spell> spell { get; set; }
}

How to serialize and deserialize (marshal and unmarshal) JSON in .NET

  • Related