Home > Backend Development > C++ > How to Efficiently Write JSON Data to a File in C#?

How to Efficiently Write JSON Data to a File in C#?

Barbara Streisand
Release: 2025-01-18 01:27:08
Original
686 people have browsed it

How to Efficiently Write JSON Data to a File in C#?

C# JSON File Writing: A Comprehensive Guide

This guide details efficient methods for writing JSON data to files in C#. The challenge lies in correctly formatting data in valid JSON syntax, including necessary brackets.

Data Model:

<code class="language-csharp">public class DataItem
{
    public int Id { get; set; }
    public int SSN { get; set; }
    public string Message { get; set; }
}</code>
Copy after login

Sample Data:

<code class="language-json">[
  {
    "Id": 1,
    "SSN": 123,
    "Message": "whatever"
  },
  {
    "Id": 2,
    "SSN": 125,
    "Message": "whatever"
  }
]</code>
Copy after login

Solution using Newtonsoft.Json (Recommended):

Newtonsoft.Json offers a highly efficient approach, avoiding string buffering.

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

// Method 1: Serialize to string, then write to file
string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(dataItems.ToArray());
System.IO.File.WriteAllText(@"D:\path.txt", jsonString);


// Method 2: Direct serialization to file stream (more efficient)
using (StreamWriter file = File.CreateText(@"D:\path2.txt"))
{
    Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
    serializer.Serialize(file, dataItems);
}</code>
Copy after login

Solution using System.Text.Json (.NET Core 3.0 and later):

System.Text.Json is a built-in library providing similar functionality with asynchronous capabilities.

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

List<DataItem> dataItems = new List<DataItem>();
dataItems.Add(new DataItem { Id = 1, SSN = 2, Message = "A Message" });

// Synchronous method
string jsonString = JsonSerializer.Serialize(dataItems);
File.WriteAllText(@"D:\path.json", jsonString);

// Asynchronous method
await using FileStream createStream = File.Create(@"D:\pathAsync.json");
await JsonSerializer.SerializeAsync(createStream, dataItems);</code>
Copy after login

Choose the method that best suits your project's needs and .NET version. For optimal performance, especially with large datasets, the direct file stream serialization (Method 2 using Newtonsoft.Json or the asynchronous method using System.Text.Json) is recommended.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template