Working with JSON files in C Sharp (C#) - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When working with JSON files in C#, it's important to understand how the time to read or write data grows as the file size increases.
We want to know how the program's running time changes when the JSON file gets bigger.
Analyze the time complexity of the following code snippet.
using System.Text.Json;
using System.IO;
using System.Collections.Generic;
string jsonString = File.ReadAllText("data.json");
var data = JsonSerializer.Deserialize<List<Person>>(jsonString);
foreach (var person in data)
{
Console.WriteLine(person.Name);
}
This code reads a JSON file, converts it into a list of objects, and then prints each person's name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each person in the list to print their name.
- How many times: Once for each person in the JSON data (n times).
As the number of people in the JSON file grows, the time to read and print their names grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 reads and prints |
| 100 | About 100 reads and prints |
| 1000 | About 1000 reads and prints |
Pattern observation: The work grows directly with the number of items; doubling the data doubles the work.
Time Complexity: O(n)
This means the time to process the JSON file grows in a straight line with the number of items inside it.
[X] Wrong: "Reading a JSON file always takes the same time no matter how big it is."
[OK] Correct: The bigger the file and the more items inside, the longer it takes to read and process each item.
Understanding how reading and processing JSON scales helps you write efficient programs and answer questions about data handling in interviews.
"What if we changed the code to only read and print the first 10 items regardless of file size? How would the time complexity change?"
Practice
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]
- Thinking JSON compiles code
- Confusing JSON with UI design
- Assuming JSON manages databases
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]
- Using non-existent methods like ReadJson
- Confusing JsonSerializer with file reading
- Using JsonConvert without importing Newtonsoft
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; }
}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]
- Expecting JSON string printed directly
- Confusing property names or types
- Ignoring deserialization step
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; }
}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]
- Using ToString() instead of serialization
- Assuming WriteAllText can't write JSON
- Thinking class must be static to serialize
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?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]
- Passing filename directly to Deserialize
- Using ReadAllLines instead of ReadAllText
- Setting deserialized list to null immediately
