gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:41:51 25 4
gpt4 key购买 nike

我需要在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com