繁体   English   中英

将 a.json 文件反序列化为 c# 中的字典

[英]Deserializing a .json file to a dictionary in c#

我正在尝试反序列化我已经能够序列化为 .json 文件的字典。 我制作了一个 class 的“时间表”,基本上如下所示:

Dictionary<Dag, Stack<Training>>

在我的数据层中,我有以下 .json 文件:

 {
  "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": []
  }
}

如您所见,它有一堆训练对象的日子。 但我无法将其反序列化回字典,如上所示。

这是一个学校项目,所以我不能使用 Newtonsoft,我必须使用 System.Text.JSON

这是我现在的代码:

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;
    }

提前致谢!

您可以解析 json 字符串,然后反序列化 FullSchedule 值

var jsonDocument = JsonDocument.Parse(scheduleString);

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

根据它的外观,您的 json 将在这样的 class 中反序列化:

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

暂无
暂无

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

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