问题描述
我需要在 C# 中使用 JSON 格式将以下数据写入文本文件.括号很重要,因为它是有效的 JSON 格式.
[{身份证":1,社会保障号":123,消息":随便"},{身份证":2,社会保障号":125,消息":随便"}]这是我的模型类:
公共类数据{公共 int Id { 获取;放;}公共 int SSN { 获取;放;}公共字符串消息 { 获取;放;}}
2020 年更新: 我写这个答案已经 7 年了.它似乎仍然受到很多关注.2013 年,Newtonsoft Json.Net 是这个问题的答案.现在它仍然是这个问题的很好的答案,但它不再是唯一可行的选择.要为此答案添加一些最新的警告:
- .Net Core 现在有类似的
System.Text.Json
序列化器(见下文) JavaScriptSerializer
幸运地通过了,这个类甚至不在 .Net Core 中.这使 Newtonsoft 进行的许多比较无效.- 最近我也注意到了,通过我们在工作中使用的一些漏洞扫描软件,Json.Net 已经有一段时间没有更新了.2020 年的更新已经枯竭,最新版本 12.0.3 已经结束一岁(2021 年).
- 速度测试(之前在下面引用 但现在已删除,因为它们已经过时以至于它们似乎无关紧要)正在比较旧版本的 Json.Net(6.0 版,就像我说的那样)最新的是 12.0.3),带有过时的 .Net Framework 序列化器.
System.Text.Json
序列化程序与 Newtonsoft 相比的一个优势是它支持async
/await
Json.Net 的日子已经屈指可数了吗?它仍然被大量使用,并且仍然被 MS 库使用.所以可能不是.但这确实感觉就像是这个图书馆结束的开始,它很可能只是运行它的课程.
.Net Core 3.0+ 和 .Net 5
自从写这篇文章以来,一个新的孩子是System.Text.Json
已添加到 .Net Core 3.0.微软声称现在比 Newtonsoft 更好.包括它比 Newtonsoft 快.我建议你自己测试一下.
示例:
使用 System.Text.Json;使用 System.Text.Json.Serialization;列表<数据>_data = 新列表();_data.Add(新数据(){编号 = 1,社会保障号码 = 2,消息 = 一条消息"});字符串 json = JsonSerializer.Serialize(_data);File.WriteAllText(@"D:path.json", json);
或
使用 System.Text.Json;使用 System.Text.Json.Serialization;列表<数据>_data = 新列表();_data.Add(新数据(){编号 = 1,社会保障号码 = 2,消息 = 一条消息"});使用 FileStream createStream = File.Create(@"D:path.json");等待 JsonSerializer.SerializeAsync(createStream, _data);
Newtonsoft Json.Net(.Net 框架和 .Net Core)
另一种选择是Json.Net,见下例:
List_data = 新列表();_data.Add(新数据(){编号 = 1,社会保障号码 = 2,消息 = 一条消息"});字符串 json = JsonConvert.SerializeObject(_data.ToArray());//将字符串写入文件System.IO.File.WriteAllText(@D:path.txt", json);
或者上面代码稍微更高效的版本(不使用字符串作为缓冲区):
//打开文件流使用 (StreamWriter file = File.CreateText(@D:path.txt")){JsonSerializer 序列化器 = new JsonSerializer();//将对象直接序列化为文件流serializer.Serialize(file, _data);}
[
{
"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;}
}
- .Net Core now has the spookily similar
System.Text.Json
serialiser (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 forasync
/await
Are Json.Net's days numbered? It's still used a LOT and it's still used by MS libraries. So probably not. But this does feel like the beginning of the end for this library that may well of just run it's course.
.Net Core 3.0+ and .Net 5
A new kid on the block since writing this is System.Text.Json
which has been added to .Net Core 3.0. Microsoft makes several claims to how this is, now, better than Newtonsoft. Including that it is faster than Newtonsoft. I'd advise you to test this yourself .
Examples:
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"
});
using FileStream createStream = File.Create(@"D:path.json");
await JsonSerializer.SerializeAsync(createStream, _data);
Newtonsoft Json.Net (.Net framework and .Net Core)
Another option is Json.Net, see example below:
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);
Or the slightly more efficient version of the above code (doesn't use a string as a buffer):
//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);
}
Documentation: Serialize JSON to a file
这篇关于如何在 C# 中编写 JSON 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!