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

Working with JSON files in C Sharp (C#) - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
JSON Master in C#
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this JSON serialization code?

Consider the following C# code that serializes an object to JSON. What will be printed?

C Sharp (C#)
using System;
using System.Text.Json;

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

public class Program {
    public static void Main() {
        var person = new Person { Name = "Alice", Age = 30 };
        string json = JsonSerializer.Serialize(person);
        Console.WriteLine(json);
    }
}
A{"Name":Alice,"Age":30}
B{"name":"Alice","age":30}
C{"Name":"Alice","Age":30}
D{Name:"Alice",Age:30}
Attempts:
2 left
💡 Hint

Remember that property names are serialized with exact casing by default.

Predict Output
intermediate
2:00remaining
What error does this JSON deserialization code produce?

What error will this code produce when trying to deserialize the JSON string?

C Sharp (C#)
using System;
using System.Text.Json;

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

public class Program {
    public static void Main() {
        string json = "{\"Name\":\"Bob\", \"Age\":\"thirty\"}";
        var person = JsonSerializer.Deserialize<Person>(json);
        Console.WriteLine(person.Name);
    }
}
ASystem.NullReferenceException
BSystem.Text.Json.JsonException
CSystem.FormatException
DNo error, prints 'Bob'
Attempts:
2 left
💡 Hint

Check the type of the 'Age' property and the JSON value type.

🔧 Debug
advanced
2:30remaining
Why does this JSON serialization ignore a property?

Given this class and serialization code, why is the 'Password' property missing in the JSON output?

C Sharp (C#)
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

public class User {
    public string Username { get; set; }
    [JsonIgnore]
    public string Password { get; set; }
}

public class Program {
    public static void Main() {
        var user = new User { Username = "user1", Password = "secret" };
        string json = JsonSerializer.Serialize(user);
        Console.WriteLine(json);
    }
}
APassword is private and cannot be serialized.
BThe serializer only serializes string properties named Username.
CPassword is null so it is not serialized.
DThe [JsonIgnore] attribute tells the serializer to skip the Password property.
Attempts:
2 left
💡 Hint

Look at the attributes above the Password property.

📝 Syntax
advanced
2:30remaining
Which option correctly deserializes JSON with a custom property name?

Given this JSON string and class, which code correctly deserializes the JSON?

{"full_name":"John Doe","Age":25}

Class:

public class Person {
    [JsonPropertyName("full_name")]
    public string Name { get; set; }
    public int Age { get; set; }
}
Avar person = JsonSerializer.Deserialize<Person>(json);
Bvar person = JsonSerializer.Deserialize<Person>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
Cvar person = JsonSerializer.Deserialize<Person>(json, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
Dvar person = JsonSerializer.Deserialize<Person>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = false });
Attempts:
2 left
💡 Hint

The attribute [JsonPropertyName] maps JSON property names to class properties.

🚀 Application
expert
3:00remaining
How many items are in the dictionary after this JSON deserialization?

Given this JSON string and code, how many key-value pairs does the resulting dictionary contain?

{"a":1,"b":2,"c":3}

Code:

using System;
using System.Text.Json;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        string json = "{\"a\":1,\"b\":2,\"c\":3}";
        var dict = JsonSerializer.Deserialize>(json);
        Console.WriteLine(dict.Count);
    }
}
A3
B0
C1
DThrows an exception
Attempts:
2 left
💡 Hint

Count the number of properties in the JSON object.

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