2020年更新:我写这个答案已经7年了。它似乎仍然得到了很多关注。2013年Newtonsoft Json。网络是这个问题的答案。现在它仍然是这个问题的一个很好的答案,但它不再是唯一可行的选择。在这个答案中添加一些最新的警告:
.NET Core now has the spookily similar System.Text.Json serializer (see below)
The days of the JavaScriptSerializer have thankfully passed and this class isn't even in .NET Core. This invalidates a lot of the comparisons ran by Newtonsoft.
It's also recently come to my attention, via some vulnerability scanning software we use in work that Json.Net hasn't had an update in some time. Updates in 2020 have dried up and the latest version, 12.0.3, is over a year old (2021).
The speed tests (previously quoted below but now removed as they are so out of date that they seem irrelevant) are comparing an older version of Json.Net (version 6.0 and like I said the latest is 12.0.3) with an outdated .Net Framework serialiser.
One advantage the System.Text.Json serializer has over Newtonsoft is it's support for async/await
是Json。网络的日子屈指可数了?它仍然被大量使用,并且仍然被MS库使用。所以可能不会。但这确实感觉像是这个图书馆结束的开始,它可能只是运行它的课程。
.NET Core 3.0+和。net 5+
自从写了这篇文章之后,一个新加入的孩子是System.Text.Json,它被添加到了。net Core 3.0中。微软多次宣称,现在它比牛顿软件(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);
or
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);
文档
Newtonsoft Json。净(。Net框架和。Net核心)
另一个选项是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);
}
文档:将JSON序列化为文件