Reading JSON in C#: Complete Guide with Examples
JSON (JavaScript Object Notation) is one of the most widely used formats for exchanging data between applications. Modern APIs, cloud services, mobile apps, and web applications frequently use JSON because it is lightweight, human-readable, and easy to process.
In this tutorial, you'll learn how to read JSON in C# using
System.Text.Json, deserialize JSON into objects,
work with arrays, handle nested data structures, and apply
best practices for real-world .NET applications.
- What is JSON?
- Reading JSON strings
- Deserializing objects
- Working with JSON arrays
- Reading nested JSON
- Reading JSON files
- Error handling
- Best practices
What Is JSON?
JSON is a text-based format used to represent structured data. It consists of key-value pairs and supports arrays, objects, strings, numbers, booleans, and null values.
Example JSON:
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
This data can easily be converted into C# objects.
System.Text.Json
Starting with .NET Core 3.0, Microsoft introduced
System.Text.Json as the recommended JSON library.
Benefits include:
- High performance
- Built into .NET
- Minimal dependencies
- Strong typing support
- Easy serialization and deserialization
Create a C# Model
Before deserializing JSON, create a class that matches the structure of the JSON data.
public class User
{
public int Id { get; set; }
public string Name { get; set; } = "";
public string Email { get; set; } = "";
}
Deserialize a JSON String
Deserialization converts JSON into a C# object.
using System.Text.Json;
string json = """
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
""";
User? user =
JsonSerializer.Deserialize<User>(json);
Console.WriteLine(user?.Name);
Output
John Doe
Working with JSON Arrays
APIs often return collections of objects.
[
{
"id": 1,
"name": "John"
},
{
"id": 2,
"name": "Jane"
}
]
Deserialize the array into a list.
List<User>? users =
JsonSerializer.Deserialize<List<User>>(json);
foreach (var user in users)
{
Console.WriteLine(user.Name);
}
Reading Nested JSON
Real-world APIs frequently return nested objects.
{
"id": 1,
"name": "John",
"address":
{
"city": "Manila",
"country": "Philippines"
}
}
Create matching classes.
public class Address
{
public string City { get; set; } = "";
public string Country { get; set; } = "";
}
public class User
{
public int Id { get; set; }
public string Name { get; set; } = "";
public Address Address { get; set; } = new();
}
The serializer automatically maps nested objects.
Reading Specific JSON Properties
Sometimes you only need a few values rather than a full model.
using System.Text.Json;
JsonDocument document =
JsonDocument.Parse(json);
string name =
document.RootElement
.GetProperty("name")
.GetString() ?? "";
Console.WriteLine(name);
This approach is useful when the structure is dynamic.
Reading JSON from a File
JSON data is often stored in files.
string json =
File.ReadAllText("user.json");
User? user =
JsonSerializer.Deserialize<User>(json);
This technique is commonly used for configuration, imports, and local data storage.
Reading JSON from an API
Many applications retrieve JSON from REST APIs.
HttpClient client = new HttpClient();
string json =
await client.GetStringAsync(
"https://api.example.com/users/1");
User? user =
JsonSerializer.Deserialize<User>(json);
This combines HttpClient and System.Text.Json to consume web services efficiently.
Case-Insensitive Property Names
JSON property names do not always match C# property casing.
var options =
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
User? user =
JsonSerializer.Deserialize<User>(
json,
options);
This helps when integrating with third-party APIs.
Error Handling
Invalid JSON can cause exceptions.
try
{
User? user =
JsonSerializer.Deserialize<User>(json);
}
catch (JsonException ex)
{
Console.WriteLine(ex.Message);
}
Proper error handling improves application reliability.
Performance Considerations
System.Text.Json is optimized for performance and memory efficiency.
To improve performance further:
- Reuse serializer options.
- Avoid unnecessary conversions.
- Deserialize only required data.
- Use strongly typed models when possible.
Common Mistakes
- Using mismatched property names.
- Ignoring null values.
- Skipping exception handling.
- Creating overly complex models.
- Assuming external JSON is always valid.
Best Practices
- Use System.Text.Json for modern .NET applications.
- Create strongly typed models.
- Validate incoming data.
- Handle exceptions properly.
- Keep JSON structures simple and maintainable.
Frequently Asked Questions
What is the best JSON library for .NET?
For most applications, System.Text.Json is the recommended choice because it is built into .NET and offers excellent performance.
Can I deserialize JSON directly into a class?
Yes. JsonSerializer.Deserialize() automatically maps JSON data to matching C# properties.
How do I read JSON from an API?
Use HttpClient to retrieve the JSON string and then deserialize it using JsonSerializer.
Can JSON contain nested objects?
Yes. Nested JSON structures can be represented using nested C# classes.
Related Tutorials
- Using HttpClient in C#
- Build a REST API in ASP.NET Core
- Async and Await in C#
- C# Dictionary Examples
- File Handling in ASP.NET Core
- Exception Handling in C#
Conclusion
Reading JSON is a fundamental skill for modern .NET developers. Whether you're consuming APIs, processing files, or exchanging data between systems, System.Text.Json provides a fast and reliable solution.
By understanding deserialization, arrays, nested objects, file handling, and error management, you can confidently work with JSON data in real-world C# applications.