【问题标题】:How to write an array to a json file in C#?如何在 C# 中将数组写入 json 文件?
【发布时间】:2019-10-12 01:20:14
【问题描述】:

我想用 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"
      }
    ]
}

编辑这是我正在使用的类:

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

我找到了将单个对象写入文件的方法,尽管我没有找到关于数组的任何内容。

如果解决方案很明显,我在浪费您的时间,请提前原谅,但我最近才开始使用 json 文件。

提前致谢,

苯乙炔

【问题讨论】:

  • 您可以使用 Dictionary<string, List<Dictionary<string, string>>> 或在此处粘贴您的 JSON:QuickType 并使用提供的类模型来序列化/反序列化 JSON。
  • 使用Json.NET库,它有你需要的一切。
  • 您的课程根本没有映射到您的 json。要获得有用的答案,您必须提供更多信息。

标签: c# json json.net


【解决方案1】:

你可以:

  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);`


【讨论】:

    猜你喜欢
    • 2013-09-07
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 2011-06-16
    相关资源
    最近更新 更多