【问题标题】:Deserializing a .json file to a dictionary in c#在 C# 中将 .json 文件反序列化为字典
【发布时间】: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


    【解决方案1】:

    根据它的外观,您的 json 将在此类中反序列化:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2019-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-08
        相关资源
        最近更新 更多