c# - 如何在 C# 中编写 JSON 文件?

标签 c# json json.net asp.net-web-api

我需要在 C# 中使用 JSON 格式将以下数据写入文本文件。括号对于它是有效的 JSON 格式很重要。

[
  {
    "Id": 1,
    "SSN": 123,
    "Message": "whatever"

  },
  {
   "Id": 2,
    "SSN": 125,
    "Message": "whatever"
  }
]

这是我的模型类:

public class data
{
    public int Id { get; set; }
    public int SSN { get; set; }
    public string Message { get; set;}
}

最佳答案

2020 年更新:我写这个答案已经 7 年了。它似乎仍然受到很多关注。 2013年Newtonsoft Json.Net是这个问题的答案。现在它仍然是解决这个问题的好方法,但它不再是唯一可行的选择。要为此答案添加一些最新的警告:

  • .NET Core 现在拥有惊人相似的 System.Text.Json 序列化程序(见下文)
  • JavaScriptSerializer 的日子谢天谢地,这个类甚至不在 .NET Core 中。这使得 Newtonsoft 进行的许多比较无效。
  • 最近我也注意到了,通过我们在工作中使用的一些漏洞扫描软件,Json.Net 已经有一段时间没有更新了。 Updates in 2020 have dried up最新版本 12.0.3 已使用一年多(2021 年)。
  • speed tests ( previously quoted below 但现在已删除,因为它们已经过时以至于它们似乎无关紧要)正在比较旧版本的 Json.Net(版本 6.0,就像我说的最新版本是 12.0.3)与一个过时的 .Net Framework 序列化器。
  • System.Text.Json 序列化程序相对于 Newtonsoft 的一个优势是它支持 async/await

Json.Net 的日子屈指可数了吗?它仍然被大量使用,并且仍然被 MS 库使用。所以可能不会。但这确实让人觉得这个图书馆很可能只是顺其自然。


.NET Core 3.0+ 和 .NET 5+

写这篇文章后,一个新来的 child 是 System.Text.Json已添加到 .Net Core 3.0。 Microsoft makes several claims to how this is, now, better than Newtonsoft .包括它是faster than Newtonsoft .我建议你自己测试一下

示例:

using System.Text.Json;
using System.Text.Json.Serialization;

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

string json = JsonSerializer.Serialize(_data);
File.WriteAllText(@"D:\path.json", json);

using System.Text.Json;
using System.Text.Json.Serialization;

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

await using FileStream createStream = File.Create(@"D:\path.json");
await JsonSerializer.SerializeAsync(createStream, _data);

Documentation


Newtonsoft Json.Net(.Net 框架和 .Net Core)

另一个选项是Json.Net ,请参见下面的示例:

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

string json = JsonConvert.SerializeObject(_data.ToArray());

//write string to file
System.IO.File.WriteAllText(@"D:\path.txt", json);

或者上面代码的稍微高效的版本(不使用字符串作为缓冲区):

//open file stream
using (StreamWriter file = File.CreateText(@"D:\path.txt"))
{
     JsonSerializer serializer = new JsonSerializer();
     //serialize object directly into file stream
     serializer.Serialize(file, _data);
}

文档:Serialize JSON to a file

关于c# - 如何在 C# 中编写 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16921652/

相关文章:

java - 如何使用 Java 序列化和反序列化来自 Google geocode 的 JSON 对象

json - 使用 swift Codable 从 JSON 数组中提取数据

json.net - 如何在 JsonPath 中过滤非数组

c# - 为什么我的内部数组没有被反序列化?

c# - 让我的第二个水平网格分离器正常工作

c# - Entity Framework 使用字符串选择表

c# - 如何获取在 C# 中使用给定文件名的 PID?

c# - C# .NET 中有什么好的像素化算法?

javascript - 我正在尝试使用 jQuery 加载要在 D3 plus 可视化中使用的 JSON 文件

c# - JSON.Net 将 json 对反序列化为对象属性