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

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

Linda Hamilton
Linda HamiltonOriginal
2025-01-18 01:32:08776browse

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

How to write JSON file in C#?

JSON syntax and data model

The JSON format requires the use of specific syntax to represent structured data. In this example, you have a JSON array containing two objects, each containing three properties: "Id", "SSN" and "Message". Your model class "data" defines these properties.

Use Newtonsoft Json.Net

Json.Net is a powerful and widely used library for processing JSON in C#. Here’s how to use it:

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

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "一条消息"
});

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

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

Json.Net provides a flexible and efficient way to serialize and deserialize JSON data, and it provides advanced features to handle complex data structures and custom serialization settings.

Use System.Text.Json (.NET Core 3.0)

.NET Core introduces the System.Text.Json namespace, which provides a built-in JSON serializer:

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

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "一条消息"
});

string json = JsonSerializer.Serialize(_data);

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

System.Text.Json focuses on performance and efficient memory usage, making it ideal for high-throughput JSON processing scenarios.

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