Home > other >  Deserializing a .json file to a dictionary in c#
Deserializing a .json file to a dictionary in c#

Time:12-10

I am trying to deserialize a dictionary that I was able to already serialize into a .json file. I made have a class 'Schedule' that is basically the following:

Dictionary<Dag, Stack<Training>>

In my data layer I have the following .json file:

 {
  "FullSchedule": {
    "Maandag": [
      {
        "Name": "test",
        "Description": "test",
        "Trainingsort": 0,
        "Hours": 1,
        "Minutes": 0
      }
    ],
    "Dinsdag": [],
    "Woensdag": [
      {
        "Name": "test",
        "Description": "test",
        "Trainingsort": 0,
        "Hours": 0,
        "Minutes": 30
      }
    ],
    "Donderdag": [],
    "Vrijdag": [],
    "Zaterdag": [],
    "Zondag": []
  }
}

As you can see it has the days with a stack of Training objects. But I am not able to deserialize it back to the dictionary as shown above.

It's a school project so I can't use the Newtonsoft and I have to use System.Text.JSON

This is the code i have at the moment:

public static Dictionary<string, Stack<Training>> ReadJSON(string path)
    {
        if (!Directory.Exists(path)) throw new ArgumentException("Path does not exist");

        // First read the file in as a string, then parse it
        string scheduleString = "";
        try
        {
            using (StreamReader sr = new StreamReader($@"{path}.json"))
            {
                scheduleString = sr.ReadToEnd();
            }
        }
        catch (Exception e) { throw new Exception(e.Message); }

        var schedule = JsonSerializer.Deserialize<Dictionary<string, Stack<Training?>>>(scheduleString);
        return schedule;
    }

Thanks in advance!

CodePudding user response:

you can parse json string and after this to deserialize a FullSchedule value

var jsonDocument = JsonDocument.Parse(scheduleString);

Dictionary<string, Stack<Training?>> schedule = jsonDocument.RootElement
  .GetProperty("FullSchedule").Deserialize<Dictionary<string, Stack<Training?>>>();

CodePudding user response:

According to how it looks, your json will be deserialized in such class:

public class SomeClass
{
    public Dictionary<string, Stack<Training?>> FullSchedule { get; set; }
}
...
var schedule = System.Text.Json.JsonSerializer.Deserialize<SomeClass>(jsonString);
  • Related