How to Read and Write JSON Files in C#

Introduction

JSON (JavaScript Object Notation) is a lightweight data format commonly used for configuration files, APIs, and data storage. In C#, you can easily handle JSON using the System.Text.Json library. This Article explains how to write JSON data to a file and read it back into a C# program using a simple example.

Create a Data Model. Define a class to represent your data structure.

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Write Data to a JSON File.

  • To save data, you convert the Product objects into JSON format and write them to a file.

Read Data from a JSON File

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

Here is the Full Code Example

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Price { get; set; } 
}

class Program
{
    static async Task Main(string[] args)
    {
        string filePath = "products.json";

        // Create some sample data
        var products = new List<Product>
        {
            new Product { Id = 1, Name = "Laptop", Price = 800.00 },
            new Product { Id = 2, Name = "Phone", Price = 500.00 }
        };

        // Write the data to a JSON file
        await WriteJsonToFileAsync(filePath, products);

        // Read the data back from the JSON file
        var loadedProducts = await ReadJsonFromFileAsync(filePath);

        // Display the data
        foreach (var product in loadedProducts)
        {
            Console.WriteLine($"Id: {product.Id}, Name: {product.Name}, Price: {product.Price}");
        }
    }

    // Method to write data to a JSON file
    static async Task WriteJsonToFileAsync(string filePath, List<Product> products)
    {
        string json = JsonSerializer.Serialize(products, new JsonSerializerOptions { WriteIndented = true });
        await File.WriteAllTextAsync(filePath, json);
    }

    // Method to read data from a JSON file
    static async Task<List<Product>> ReadJsonFromFileAsync(string filePath)
    {
        string json = await File.ReadAllTextAsync(filePath);
        return JsonSerializer.Deserialize<List<Product>>(json);
    }
}

After running the program, the JSON file will look like this

[
  {
    "Id": 1,
    "Name": "Laptop",
    "Price": 800.0
  },
  {
    "Id": 2,
    "Name": "Phone",
    "Price": 500.0
  }
]

Console Output

Id: 1, Name: Laptop, Price: 800
Id: 2, Name: Phone, Price: 500

Why is this Useful?

  • Storing Data: Save application data in JSON format.
  • Configuration Files: JSON files are often used for application settings.
  • API Responses: Many APIs return data in JSON format, making this skill valuable for API integration.

With this knowledge, you can efficiently handle JSON files in your C# projects for a variety of use cases.


Similar Articles