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.
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>
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>
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!