Introduction to Working with JSON in C#
JSON (JavaScript Object Notation) is a lightweight data interchange format widely used in modern web applications, APIs, and configuration files. For a C# developer, the ability to work with JSON is an essential skill, especially when building REST clients, microservices, or applications interacting with external data sources.
In the .NET ecosystem, there are two main approaches to processing JSON: the classic library Newtonsoft.Json (also known as Json.NET) and the modern built-in library System.Text.Json, introduced in .NET Core 3.0 and becoming the standard in .NET 5+. Both libraries allow you to perform two key operations: serialization (converting a C# object to a JSON string) and deserialization (converting a JSON string back to a C# object).
In this article, we will thoroughly examine both approaches, learn how to parse complex data structures, and review best practices for working with JSON in C#.
1. Basic Operations: Serialization and Deserialization
1.1 Using Newtonsoft.Json (Json.NET)
Newtonsoft.Json has been the de facto standard for working with JSON in .NET for many years. To get started, install the package via NuGet:
Install-Package Newtonsoft.JsonLet's consider a simple example class:
public class User{ public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } public bool IsActive { get; set; }}Serializing an object to JSON:
using Newtonsoft.Json;
User user = new User{ Id = 1, Name = "Ivan Petrov", Email = "ivan@example.com", IsActive = true};
string json = JsonConvert.SerializeObject(user, Formatting.Indented);Console.WriteLine(json);Execution result:
{ "Id": 1, "Name": "Ivan Petrov", "Email": "ivan@example.com", "IsActive": true}Deserializing JSON back to an object:
string jsonString = @"{""Id"":1,""Name"":""Ivan Petrov"",""Email"":""ivan@example.com"",""IsActive"":true}";User deserializedUser = JsonConvert.DeserializeObject<User>(jsonString);Console.WriteLine($"User: {deserializedUser.Name}, Email: {deserializedUser.Email}");1.2 Using System.Text.Json
Starting with .NET Core 3.0, Microsoft introduced its own library System.Text.Json, which is optimized for performance and requires no external dependencies.
Serialization:
using System.Text.Json;
User user = new User{ Id = 2, Name = "Maria Smirnova", Email = "maria@example.com", IsActive = false};
string json = JsonSerializer.Serialize(user, new JsonSerializerOptions { WriteIndented = true });Console.WriteLine(json);Deserialization:
string jsonString = @"{""Id"":2,""Name"":""Maria Smirnova"",""Email"":""maria@example.com"",""IsActive"":false}";User deserializedUser = JsonSerializer.Deserialize<User>(jsonString);Console.WriteLine($"User: {deserializedUser.Name}");2. Working with Complex Data Structures
2.1 Nested Objects and Collections
JSON often contains nested structures. Let's consider an example with a user's order array:
public class Order{ public int OrderId { get; set; } public decimal Amount { get; set; } public List<string> Items { get; set; }}
public class Customer{ public int CustomerId { get; set; } public string FullName { get; set; } public List<Order> Orders { get; set; }}Deserializing complex JSON