0
0
CsharpHow-ToBeginner · 3 min read

How to Write JSON File in C# Easily

To write a JSON file in C#, use System.Text.Json.JsonSerializer.Serialize to convert your object to a JSON string, then save it with File.WriteAllText. This method is simple and efficient for saving data in JSON format.
📐

Syntax

Use JsonSerializer.Serialize(object) to convert an object to a JSON string. Then use File.WriteAllText(path, jsonString) to write that string to a file.

  • object: The data you want to save as JSON.
  • path: The file path where JSON will be saved.
  • jsonString: The JSON text generated from the object.
csharp
using System.Text.Json;
using System.IO;

// Convert object to JSON string
string jsonString = JsonSerializer.Serialize(yourObject);

// Write JSON string to file
File.WriteAllText("path/to/file.json", jsonString);
💻

Example

This example shows how to create a simple object, convert it to JSON, and write it to a file named data.json.

csharp
using System;
using System.Text.Json;
using System.IO;

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

class Program
{
    static void Main()
    {
        var person = new Person { Name = "Alice", Age = 30 };

        string jsonString = JsonSerializer.Serialize(person);

        File.WriteAllText("data.json", jsonString);

        Console.WriteLine("JSON file written successfully.");
    }
}
Output
JSON file written successfully.
⚠️

Common Pitfalls

Common mistakes include:

  • Not including using System.Text.Json; or using System.IO;.
  • Trying to serialize objects with circular references, which causes errors.
  • Writing to a file path without proper permissions or invalid paths.
  • Forgetting to handle exceptions when writing files.

Always ensure your object is serializable and the file path is valid.

csharp
/* Wrong way: Missing using directives and no error handling */
// JsonSerializer.Serialize(person);
// File.WriteAllText("data.json", jsonString);

/* Right way: Include namespaces and handle exceptions */
using System;
using System.Text.Json;
using System.IO;

try
{
    var person = new { Name = "Bob", Age = 25 };
    string jsonString = JsonSerializer.Serialize(person);
    File.WriteAllText("data.json", jsonString);
    Console.WriteLine("File saved.");
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}
📊

Quick Reference

Summary tips for writing JSON files in C#:

  • Use JsonSerializer.Serialize to convert objects to JSON.
  • Use File.WriteAllText to save JSON strings to files.
  • Include using System.Text.Json; and using System.IO;.
  • Handle exceptions to avoid runtime errors.
  • Ensure file paths are correct and accessible.

Key Takeaways

Use System.Text.Json.JsonSerializer.Serialize to convert objects to JSON strings.
Write JSON strings to files with File.WriteAllText providing a valid file path.
Always include necessary namespaces: System.Text.Json and System.IO.
Handle exceptions to manage file writing errors gracefully.
Avoid serializing objects with circular references to prevent errors.