How to read and write json file in c#

By FoxLearn 11/19/2024 7:44:13 AM   17
In C#, you can read and write JSON to a file using the System.Text.Json library.

JSON is a lightweight, text-based data format used for representing structured data. It is commonly utilized for configuration files, API communication, and data storage due to its simplicity and ease of use.

Define a class to represent your data structure.

public class Person
{
     public int Id { get; set; }
     public string Name { get; set; }
     public int Age { get; set; }
}

To save data, you convert the `Person` objects into JSON format and write the resulting JSON to a file.

// Create a sample object
var person = new Person() { Id = 1, Name = "John Doe", Age = 30 };

// Serialize the object to JSON
string jsonString = JsonSerializer.Serialize(person);

// c# Write JSON string to file
File.WriteAllText("person.json", jsonString);

To load the data, you read the JSON content from the file and convert it back into a list of `Person` objects.

For example:

// c# read JSON string from file
string jsonString = File.ReadAllText("person.json");

// Deserialize JSON string into object
Person person = JsonSerializer.Deserialize<Person>(jsonString);

You can also create a method to write data to a JSON file like this:

async Task WriteJsonToFileAsync(string fileName, List<Person> persons)
{
    string json = JsonSerializer.Serialize(persons, new JsonSerializerOptions { WriteIndented = true });
    await File.WriteAllTextAsync(fileName, json);
}

You can also create a method to read data from a JSON file like this:

async Task<List<Person>> ReadJsonFromFileAsync(string fileName)
{
    string json = await File.ReadAllTextAsync(fileName);
    return JsonSerializer.Deserialize<List<Person>>(json);
}

For example read and write json file in C#:

string fileName = "data.json";

// Create sample objects
var persons = new List<Person>
{
     new Person{ Id = 1, Name = "John Doe", Age = 30 },
     new Person { Id = 2, Name = "Lucy", Age = 26 }
};
// c# write the data to a JSON file
await WriteJsonToFileAsync(fileName, persons);

Next, we will read json file, then convert to list object in c#.

// c# read JSON file to object
var persons = await ReadJsonFromFileAsync(fileName);

// Display the data
foreach (var person in persons)
{
     Console.WriteLine($"Id: {person.Id}, Name: {person.Name}, Age: {person.Age}");
}