JSON files let programs save and share data in a simple text format. Working with JSON files helps your program read and write data easily.
Working with JSON files in C Sharp (C#)
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
C Sharp (C#)
using System.Text.Json; using System.IO; // To read JSON from a file string jsonString = File.ReadAllText("file.json"); var data = JsonSerializer.Deserialize<YourType>(jsonString); // To write JSON to a file string output = JsonSerializer.Serialize(data); File.WriteAllText("file.json", output);
Use JsonSerializer from System.Text.Json namespace for easy JSON handling.
Replace YourType with the class that matches your JSON structure.
Examples
C Sharp (C#)
using System.Text.Json; using System.IO; // Reading JSON into a dictionary string jsonString = File.ReadAllText("data.json"); var dict = JsonSerializer.Deserialize<Dictionary<string, string>>(jsonString);
C Sharp (C#)
using System.Text.Json; using System.IO; // Writing an object to JSON file var person = new { Name = "Anna", Age = 28 }; string json = JsonSerializer.Serialize(person); File.WriteAllText("person.json", json);
Sample Program
This program saves a user object to a JSON file and then reads it back to show the data.
C Sharp (C#)
using System; using System.IO; using System.Text.Json; class Program { public class User { public string Name { get; set; } public int Age { get; set; } } static void Main() { // Create a user object var user = new User { Name = "John", Age = 30 }; // Convert user to JSON string string jsonString = JsonSerializer.Serialize(user); // Save JSON string to file File.WriteAllText("user.json", jsonString); // Read JSON string back from file string readJson = File.ReadAllText("user.json"); // Convert JSON string back to User object var userFromFile = JsonSerializer.Deserialize<User>(readJson); // Show user info Console.WriteLine($"Name: {userFromFile.Name}, Age: {userFromFile.Age}"); } }
Important Notes
Make sure your classes have public properties with getters and setters for JSON serialization.
If the JSON file is missing or corrupted, reading it will cause an error, so handle exceptions in real apps.
Summary
JSON files store data in a simple text format easy to read and write.
Use JsonSerializer to convert between objects and JSON strings.
Read JSON from files with File.ReadAllText and write with File.WriteAllText.
Practice
1. What is the main purpose of using JSON files in C# programming?
easy
Solution
Step 1: Understand JSON file usage
JSON files store data in a readable text format that can be shared or saved easily.Step 2: Identify the correct purpose
Among the options, only storing and exchanging data matches JSON's role.Final Answer:
To store and exchange data in a simple text format -> Option AQuick Check:
JSON = data storage and exchange [OK]
Hint: JSON files hold data as text for easy sharing [OK]
Common Mistakes:
- Thinking JSON compiles code
- Confusing JSON with UI design
- Assuming JSON manages databases
2. Which of the following is the correct way to read a JSON file content into a string in C#?
easy
Solution
Step 1: Recall file reading method in C#
The method File.ReadAllText reads all text from a file into a string.Step 2: Check method correctness
Only File.ReadAllText("data.json") is valid syntax to read JSON as string.Final Answer:
string json = File.ReadAllText("data.json"); -> Option BQuick Check:
File.ReadAllText reads file content [OK]
Hint: Use File.ReadAllText to read JSON file content [OK]
Common Mistakes:
- Using non-existent methods like ReadJson
- Confusing JsonSerializer with file reading
- Using JsonConvert without importing Newtonsoft
3. Given the following code, what will be the output?
using System.Text.Json;
var json = "{\"Name\":\"Alice\", \"Age\":30}";
var person = JsonSerializer.Deserialize<Person>(json);
Console.WriteLine(person.Name + " is " + person.Age + " years old.");
public class Person {
public string Name { get; set; }
public int Age { get; set; }
}medium
Solution
Step 1: Deserialize JSON string to Person object
The JsonSerializer converts the JSON string into a Person object with Name = "Alice" and Age = 30.Step 2: Print the formatted string
The Console.WriteLine outputs "Alice is 30 years old." by accessing person.Name and person.Age.Final Answer:
Alice is 30 years old. -> Option AQuick Check:
Deserialization + property access = output string [OK]
Hint: Deserialize JSON then access properties for output [OK]
Common Mistakes:
- Expecting JSON string printed directly
- Confusing property names or types
- Ignoring deserialization step
4. What is wrong with this code snippet that tries to write an object to a JSON file?
using System.Text.Json;
using System.IO;
var person = new Person { Name = "Bob", Age = 25 };
File.WriteAllText("person.json", person.ToString());
public class Person {
public string Name { get; set; }
public int Age { get; set; }
}medium
Solution
Step 1: Analyze how object is converted to JSON
Calling person.ToString() returns the class name, not JSON text.Step 2: Identify correct serialization method
Use JsonSerializer.Serialize(person) to convert the object to JSON string before writing.Final Answer:
person.ToString() does not convert the object to JSON format -> Option CQuick Check:
To write JSON, serialize object first [OK]
Hint: Use JsonSerializer.Serialize, not ToString(), to get JSON [OK]
Common Mistakes:
- Using ToString() instead of serialization
- Assuming WriteAllText can't write JSON
- Thinking class must be static to serialize
5. You want to read a JSON file containing a list of products and convert it into a List<Product> in C#. Which code snippet correctly accomplishes this?
public class Product {
public string Name { get; set; }
public double Price { get; set; }
}
// JSON file content example: [{"Name":"Pen","Price":1.5},{"Name":"Book","Price":12.99}]
// Which code correctly reads and deserializes the JSON file?hard
Solution
Step 1: Read entire JSON file as string
Use File.ReadAllText to get the JSON content from the file.Step 2: Deserialize JSON string to List<Product>
Use JsonSerializer.Deserialize(json) to convert JSON text into a list of Product objects.Final Answer:
var json = File.ReadAllText("products.json"); var products = JsonSerializer.Deserialize(json); -> Option DQuick Check:
ReadAllText + Deserialize = correct [OK]
Hint: Read file text first, then deserialize to list [OK]
Common Mistakes:
- Passing filename directly to Deserialize
- Using ReadAllLines instead of ReadAllText
- Setting deserialized list to null immediately
