Maison > développement back-end > C++ > Comment écrire un fichier JSON en C# à l'aide de Newtonsoft.Json et System.Text.Json ?

Comment écrire un fichier JSON en C# à l'aide de Newtonsoft.Json et System.Text.Json ?

Linda Hamilton
Libérer: 2025-01-18 01:37:10
original
789 Les gens l'ont consulté

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

Comment écrire un fichier JSON en C# ?

Pour écrire vos données dans un fichier texte au format JSON, vous pouvez utiliser une bibliothèque tels que Newtonsoft Json.Net ou System.Text.Json (pour .NET Core 3.0 et .NET 5 ). Explorons les deux options :

Newtonsoft Json.Net (.Net Framework et .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);
Copier après la connexion

System.Text.Json (.NET Noyau 3.0 et .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);
Copier après la connexion

System.Text.Json (sérialisation asynchrone)

// 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);
}
Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal