Home >Backend Development >C++ >How to Write a JSON File in C# Using Newtonsoft.Json and System.Text.Json?

How to Write a JSON File in C# Using Newtonsoft.Json and System.Text.Json?

Linda Hamilton
Linda HamiltonOriginal
2025-01-18 01:37:10768browse

How to Write a JSON File in C# Using Newtonsoft.Json and System.Text.Json?

How to write a JSON file in C#?

To write your data into a text file in JSON format, you can use a library such as Newtonsoft Json.Net or System.Text.Json (for .NET Core 3.0 and .NET 5 ). Let's explore both options:

Newtonsoft Json.Net (.Net Framework and .Net Core)

// Initialize your data
List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

// Serialize the data to JSON
string json = JsonConvert.SerializeObject(_data.ToArray());

// Write the JSON string to a file
System.IO.File.WriteAllText(@"D:\path.txt", json);

System.Text.Json (.NET Core 3.0 and .NET 5 )

// Initialize your data
List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

// Serialize the data to JSON (synchronously)
string json = JsonSerializer.Serialize(_data);

// Write the JSON string to a file
File.WriteAllText(@"D:\path.txt", json);

System.Text.Json (asynchronous serialization)

// Initialize your data
List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

// Serialize the data to JSON (asynchronously)
using (FileStream createStream = File.Create(@"D:\path.txt"))
{
    await JsonSerializer.SerializeAsync(createStream, _data);
}

The above is the detailed content of How to Write a JSON File in C# Using Newtonsoft.Json and System.Text.Json?. 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