簡體   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