To read and write JSONdata to a file in C#, you typically use the
System.Text.Json namespace (built-in since .NET Core 3.0+). You can also use
Newtonsoft.Json if you prefer, but here's how to do it using the built-in approach:
1. Define a C# Model
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
2. Write JSON to a File
using System.Text.Json;
using System.IO;
var person = new Person { Name = "Alice", Age = 30 };
string jsonString = JsonSerializer.Serialize(person, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText("person.json", jsonString); // Writes to file
3. Read JSON from a File
string jsonFromFile = File.ReadAllText("person.json");
Person personFromFile = JsonSerializer.Deserialize<Person>(jsonFromFile);
Console.WriteLine($"{personFromFile.Name} is {personFromFile.Age} years old.");
Notes:
JsonSerializer.Serialize(object) converts a C# object to JSON.
JsonSerializer.Deserialize<T>(json) parses JSON into a C# object.
The optional WriteIndented = true makes the JSON more readable.
Using Newtonsoft.Json (if preferred):
dotnet add package Newtonsoft.Json
Example:
using Newtonsoft.Json;
var person = new Person { Name = "Bob", Age = 25 };
File.WriteAllText("person.json", JsonConvert.SerializeObject(person, Formatting.Indented));
string json = File.ReadAllText("person.json");
Person loaded = JsonConvert.DeserializeObject<Person>(json);
Summary
Task
Built-in API
Newtonsoft.Json Equivalent
Serialize to file
JsonSerializer.Serialize
JsonConvert.SerializeObject
Deserialize from file
JsonSerializer.Deserialize
JsonConvert.DeserializeObject
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To read and write JSON data to a file in C#, you typically use the
System.Text.Jsonnamespace (built-in since .NET Core 3.0+). You can also useNewtonsoft.Jsonif you prefer, but here's how to do it using the built-in approach:1. Define a C# Model
2. Write JSON to a File
3. Read JSON from a File
Notes:
JsonSerializer.Serialize(object)converts a C# object to JSON.JsonSerializer.Deserialize<T>(json)parses JSON into a C# object.WriteIndented = truemakes the JSON more readable.Using
Newtonsoft.Json(if preferred):Example:
Summary
JsonSerializer.SerializeJsonConvert.SerializeObjectJsonSerializer.DeserializeJsonConvert.DeserializeObject