如何在 C# 中编写 JSON 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16921652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write a JSON file in C#?
提问by user1429595
I need to write the following data into a text file using JSON format in C#. The brackets are important for it to be valid JSON format.
我需要在 C# 中使用 JSON 格式将以下数据写入文本文件。括号很重要,因为它是有效的 JSON 格式。
[
{
"Id": 1,
"SSN": 123,
"Message": "whatever"
},
{
"Id": 2,
"SSN": 125,
"Message": "whatever"
}
]
Here is my model class:
这是我的模型类:
public class data
{
public int Id { get; set; }
public int SSN { get; set; }
public string Message { get; set;}
}
采纳答案by Liam
I would recommend Json.Net, see example below:
我会推荐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);
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
文档:将JSON 序列化为文件
Why? Here's a feature comparison between common serialisers as well as benchmark tests† ‡.
为什么?这是常见序列化程序和基准测试† ‡之间的功能比较。
Below is a graph of performance taken from the linked article:
以下是来自链接文章的性能图表:
This separate post, states that:
这篇单独的帖子指出:
Json.NET has always been memory efficient, streaming the reading and writing large documents rather than loading them entirely into memory, but I was able to find a couple of key places where object allocations could be reduced...... (now)Json.Net (6.0)allocates 8 times less memory than JavaScriptSerializer ‡
Json.NET 一直是内存高效的,流式读取和写入大型文档而不是将它们完全加载到内存中,但我能够找到几个可以减少对象分配的关键位置...... (现在)Json.Net (6.0)分配的内存比 JavaScriptSerializer 少 8 倍‡
Update since .Net Core 3.0
从 .Net Core 3.0 开始更新
A new kid on the block since writing this is System.Text.Jsonwhich 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. as above, I'd advise you to test this yourself ‡.
自从写这篇文章以来,一个新的孩子System.Text.Json已经被添加到 .Net Core 3.0 中。现在,微软多次声称这比 Newtonsoft 更好。包括它比 Newtonsoft 更快。如上所述,我建议您自己测试‡。
† Benchmarks appear to be Json.Net 5, the current version (on writing) is 10. What version of standard .Net serialisers used is not mentioned
† 基准似乎是 Json.Net 5,当前版本(正在编写)是 10。没有提到使用的标准 .Net 序列化程序的版本
‡ These tests are obviously from the developers who maintain the library. I have not verified their claims. If in doubt test them yourself.
‡ 这些测试显然来自维护库的开发人员。我还没有证实他们的说法。如果有疑问,请自行测试。
回答by Gabe
There is built in functionality for this using the JavaScriptSerializer Class:
有使用JavaScriptSerializer Class 的内置功能:
var json = JavaScriptSerializer.Serialize(data);
回答by Micha? S.
The example in Liam's answer saves the file as string in a single line. I prefer to add formatting. Someone in the future may want to change some value manually in the file. If you add formatting it's easier to do so.
Liam 的答案中的示例将文件作为字符串保存在一行中。我更喜欢添加格式。将来有人可能想要手动更改文件中的某些值。如果您添加格式,这样做会更容易。
The following adds basic JSON indentation:
以下添加了基本的 JSON 缩进:
string json = JsonConvert.SerializeObject(_data.ToArray(), Formatting.Indented);
回答by Kulwant Singh
var responseData = //Fetch Data
string jsonData = JsonConvert.SerializeObject(responseData, Formatting.None);
System.IO.File.WriteAllText(Server.MapPath("~/JsonData/jsondata.txt"), jsonData);


