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

How to Write JSON Files in C# Using Newtonsoft Json.Net and System.Text.Json?

Barbara Streisand
Barbara StreisandOriginal
2025-01-18 01:41:09169browse

How to Write JSON Files in C# Using Newtonsoft Json.Net and System.Text.Json?

Writing a correctly formatted JSON text file in C# requires the use of JSON serialization technology. This article will demonstrate how to use popular JSON serialization libraries such as Newtonsoft Json.Net and System.Text.Json to write JSON data.

Use Newtonsoft Json.Net

Newtonsoft Json.Net is a widely used JSON serialization library in .NET Framework and .NET Core. To write JSON data using Json.Net, follow these steps:

<code class="language-csharp">// 创建数据对象列表
List<Data> data = new List<Data>();
data.Add(new Data
{
    Id = 1,
    SSN = 123,
    Message = "whatever"
});
data.Add(new Data
{
    Id = 2,
    SSN = 125,
    Message = "whatever"
});

// 将数据序列化为字符串
string json = JsonConvert.SerializeObject(data.ToArray());

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

Use System.Text.Json

System.Text.Json is a newer JSON serialization library introduced in .NET Core 3.0. It provides similar functionality to Json.Net with additional optimizations and support for asynchronous operations.

<code class="language-csharp">// 创建数据对象列表
List<Data> data = new List<Data>();
data.Add(new Data
{
    Id = 1,
    SSN = 123,
    Message = "whatever"
});
data.Add(new Data
{
    Id = 2,
    SSN = 125,
    Message = "whatever"
});

// 将数据序列化为字符串
string json = JsonSerializer.Serialize(data);

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

Summary

Both Newtonsoft Json.Net and System.Text.Json provide effective methods for writing JSON data in C#. Which library to choose depends on the specific needs of your project.

The above is the detailed content of How to Write JSON Files in C# Using Newtonsoft Json.Net 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