如何在C#中将数组写入json文件?

问题描述 投票:-2回答:1

我想从C#代码编写一个json文件,就像下面的json文件看起来一样:

{
    "Monday": [
      {
        "class": "Example",
        "time": "09:00"
      },
      {
        "class": "Example2",
        "time": "09:50"
      }
    ],

    "Tuesday": [
      {
        "class": "Example3",
        "time": "09:00"
      },
      {
        "class": "Example4",
        "time": "09:50"
      }
    ]
}

EDIT这是我正在使用的课程:

public class Lesson {
      public string title { get; set; }
      public string timeStart { get; set; }
      public string timeEnd { get; set; }
}

尽管我对数组一无所知,但我已经找到了将单个对象写入文件的方法。

如果解决方案显而易见,请事先打扰,我在浪费您的时间,但是我最近才开始使用json文件。

谢谢,

bezunyl

c# json json.net
1个回答
0
投票

您可以:

  1. 将Json.NET添加到您的项目中
  2. 创建Dictionary<string,List<Lesson>>
  3. 呼叫JsonConver.SerializeObject(dict)

这里是如何与字典进行交互的许多可能方式的示例。

dict["Monday"]= new List<Lesson>();
dict["Monday"].Add(new Lesson(...));

When calling SerializeObject you can specify formatting as Indented: `JsonConvert.SerializeObject(o, Formatting.Indented);`


© www.soinside.com 2019 - 2024. All rights reserved.