【发布时间】:2022-12-10 00:41:42
【问题描述】:
我正在尝试反序列化我已经能够序列化为 .json 文件的字典。 我制作了一个“日程表”类,基本上如下所示:
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;
}
提前致谢!
【问题讨论】:
标签: c# json .net deserialization