Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Working with JSON files in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Working with JSON files
Start Program
Read JSON File
Parse JSON to Object
Use Object Data
Modify Object (optional)
Serialize Object to JSON
Write JSON to File
End Program
The program reads a JSON file, converts it to an object, optionally modifies it, then writes it back as JSON.
Execution Sample
C Sharp (C#)
using System.Text.Json;

string json = File.ReadAllText("data.json");
var person = JsonSerializer.Deserialize<Person>(json);
person.Age += 1;
string newJson = JsonSerializer.Serialize(person);
File.WriteAllText("data.json", newJson);
This code reads a JSON file, deserializes it into a Person object, increases the age by 1, then writes the updated JSON back.
Execution Table
StepActionCode LineVariable StateOutput/File Content
1Read JSON file contentstring json = File.ReadAllText("data.json");json = '{"Name":"Alice","Age":30}'File content read as string
2Deserialize JSON to Person objectvar person = JsonSerializer.Deserialize<Person>(json);person = Person{Name="Alice", Age=30}No output
3Increase person's age by 1person.Age += 1;person = Person{Name="Alice", Age=31}No output
4Serialize Person object to JSON stringstring newJson = JsonSerializer.Serialize(person);newJson = '{"Name":"Alice","Age":31}'No output
5Write updated JSON string to fileFile.WriteAllText("data.json", newJson);person unchangedFile content updated to '{"Name":"Alice","Age":31}'
6End programEndperson unchangedFile saved with updated JSON
💡 Program ends after writing updated JSON back to file.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5Final
jsonnull{"Name":"Alice","Age":30}{"Name":"Alice","Age":30}{"Name":"Alice","Age":30}{"Name":"Alice","Age":30}{"Name":"Alice","Age":30}{"Name":"Alice","Age":30}
personnullnullPerson{Name="Alice", Age=30}Person{Name="Alice", Age=31}Person{Name="Alice", Age=31}Person{Name="Alice", Age=31}Person{Name="Alice", Age=31}
newJsonnullnullnullnull{"Name":"Alice","Age":31}{"Name":"Alice","Age":31}{"Name":"Alice","Age":31}
Key Moments - 3 Insights
Why do we need to deserialize JSON before using it?
Because JSON is a text format, deserialization converts it into a C# object we can work with, as shown in step 2 of the execution_table.
What happens if we forget to write the updated JSON back to the file?
The file will not reflect changes made to the object in memory. Step 5 shows writing back is necessary to save changes.
Why do we serialize the object again before writing to the file?
Serialization converts the C# object back into JSON text format, which is needed to save it as a file, as shown in step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'person.Age' after step 3?
A31
B30
C29
Dnull
💡 Hint
Check the 'Variable State' column at step 3 in the execution_table.
At which step is the JSON string first read from the file?
AStep 2
BStep 4
CStep 1
DStep 5
💡 Hint
Look at the 'Action' column to find when the file content is read.
If we skip serialization (step 4), what will happen when writing to the file in step 5?
AThe file will be empty
BThe file will contain the object directly (invalid format)
CThe file will contain the old JSON
DThe program will crash
💡 Hint
Consider what File.WriteAllText expects as input and what happens if we pass an object instead of a string.
Concept Snapshot
Working with JSON files in C#:
- Read JSON text from file with File.ReadAllText
- Convert JSON text to object using JsonSerializer.Deserialize<T>
- Modify object properties as needed
- Convert object back to JSON text with JsonSerializer.Serialize
- Write JSON text back to file with File.WriteAllText
Always deserialize before use and serialize before saving.
Full Transcript
This example shows how to work with JSON files in C#. First, the program reads the JSON content from a file as a string. Then it converts this JSON string into a C# object using deserialization. After that, it modifies the object's data, for example increasing the age by one. Next, it converts the updated object back into a JSON string by serialization. Finally, it writes this new JSON string back to the file, saving the changes. This process ensures that the program can read, use, and update JSON data stored in files.

Practice

(1/5)
1. What is the main purpose of using JSON files in C# programming?
easy
A. To store and exchange data in a simple text format
B. To compile C# code faster
C. To create graphical user interfaces
D. To manage database connections

Solution

  1. Step 1: Understand JSON file usage

    JSON files store data in a readable text format that can be shared or saved easily.
  2. Step 2: Identify the correct purpose

    Among the options, only storing and exchanging data matches JSON's role.
  3. Final Answer:

    To store and exchange data in a simple text format -> Option A
  4. Quick 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
A. string json = JsonSerializer.ReadFile("data.json");
B. string json = File.ReadAllText("data.json");
C. string json = File.ReadJson("data.json");
D. string json = JsonConvert.Read("data.json");

Solution

  1. Step 1: Recall file reading method in C#

    The method File.ReadAllText reads all text from a file into a string.
  2. Step 2: Check method correctness

    Only File.ReadAllText("data.json") is valid syntax to read JSON as string.
  3. Final Answer:

    string json = File.ReadAllText("data.json"); -> Option B
  4. Quick 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
A. Alice is 30 years old.
B. Name is Alice, Age is 30
C. System.Text.Json.JsonException
D. null is 0 years old.

Solution

  1. Step 1: Deserialize JSON string to Person object

    The JsonSerializer converts the JSON string into a Person object with Name = "Alice" and Age = 30.
  2. Step 2: Print the formatted string

    The Console.WriteLine outputs "Alice is 30 years old." by accessing person.Name and person.Age.
  3. Final Answer:

    Alice is 30 years old. -> Option A
  4. Quick 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
A. File.WriteAllText cannot write to JSON files
B. Person class must be static to serialize
C. person.ToString() does not convert the object to JSON format
D. Missing using directive for System.IO

Solution

  1. Step 1: Analyze how object is converted to JSON

    Calling person.ToString() returns the class name, not JSON text.
  2. Step 2: Identify correct serialization method

    Use JsonSerializer.Serialize(person) to convert the object to JSON string before writing.
  3. Final Answer:

    person.ToString() does not convert the object to JSON format -> Option C
  4. Quick 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
A. var products = JsonSerializer.Deserialize(File.ReadAllText("products.json")); products = null;
B. var products = JsonSerializer.Deserialize("products.json");
C. var products = JsonSerializer.Deserialize(File.ReadAllLines("products.json"));
D. var json = File.ReadAllText("products.json"); var products = JsonSerializer.Deserialize(json);

Solution

  1. Step 1: Read entire JSON file as string

    Use File.ReadAllText to get the JSON content from the file.
  2. Step 2: Deserialize JSON string to List<Product>

    Use JsonSerializer.Deserialize(json) to convert JSON text into a list of Product objects.
  3. Final Answer:

    var json = File.ReadAllText("products.json"); var products = JsonSerializer.Deserialize(json); -> Option D
  4. Quick 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