Home >Backend Development >C++ >How to Efficiently Save JSON Data in C#?

How to Efficiently Save JSON Data in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-18 01:46:09154browse

How to Efficiently Save JSON Data in C#?

C# JSON data saving method

This article introduces several methods of writing JSON data to files in C#:

Method 1: Use Newtonsoft Json.Net

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

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

// 将字符串写入文件
System.IO.File.WriteAllText(@"D:\path.txt", json);</code>

Method 2: Use System.Text.Json (.NET Core 3.0 and above)

<code class="language-csharp">using System.Text.Json;

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);</code>

Method 3: Use StreamWriter (more efficient)

<code class="language-csharp">// 打开文件流
using (StreamWriter file = File.CreateText(@"D:\path.txt"))
{
    JsonSerializer serializer = new JsonSerializer();
    // 直接将对象序列化到文件流
    serializer.Serialize(file, _data);
}</code>

Please note that in order to ensure the validity of the JSON format, correct brackets need to be used.

The above is the detailed content of How to Efficiently Save JSON Data in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn