Introduction to Working with JSON in C#
JSON (JavaScript Object Notation) is a lightweight data interchange format widely used in web development, configuration files, and APIs. If you are starting to learn C# and .NET, the ability to work with JSON is a must-have skill. In this article, we will cover how to perform JSON parsing (converting a string to an object) and serialization (converting an object to a JSON string) using built-in .NET tools and the popular Newtonsoft.Json library.
We will look at practical examples that will help you quickly master the key concepts. All code is written in C# (.NET 6+), but will work in earlier versions with minimal changes.
1. Built-in JSON Support: System.Text.Json Namespace
Starting with .NET Core 3.0, Microsoft introduced the high-performance System.Text.Json namespace. It is built into the platform and does not require installing additional packages. This is the primary tool for working with JSON in modern .NET applications.
1.1 Serializing an Object to JSON
Serialization is the process of converting a C# object into a JSON string. Consider a simple Person class:
public class Person{ public string Name { get; set; } public int Age { get; set; } public string Email { get; set; }}
// Usagevar person = new Person{ Name = "Ivan Ivanov", Age = 30, Email = "ivan@example.com"};
string json = System.Text.Json.JsonSerializer.Serialize(person);Console.WriteLine(json);Output:
{"Name":"Ivan Ivanov","Age":30,"Email":"ivan@example.com"}By default, properties are serialized with names matching the C# property names. You can customize formatting using JsonSerializerOptions, for example, to make the JSON more readable:
var options = new System.Text.Json.JsonSerializerOptions{ WriteIndented = true};
string prettyJson = JsonSerializer.Serialize(person, options);Console.WriteLine(prettyJson);Now the output will be indented:
{ "Name": "Ivan Ivanov", "Age": 30, "Email": "ivan@example.com"}1.2 Deserialization (Parsing) JSON into an Object
The reverse process — converting a JSON string into a C# object — is called deserialization. Use the JsonSerializer.Deserialize<T>() method:
string jsonString = @"{""Name"":""Maria Petrova"",""Age"":25,""Email"":""maria@example.com""}";
Person? person = System.Text.Json.JsonSerializer.Deserialize<Person>(jsonString);
if (person != null){ Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");}Important: if the JSON does not match the class structure, a JsonException will be thrown. For safe operation, use exception handling or check for null.
1.3 Working with JsonDocument for Arbitrary JSON
Sometimes the JSON structure is unknown in advance, or you want to read data without creating classes. For this, use JsonDocument:
string jsonText = @"{""product"":""Laptop"",""price"":75000,""inStock"":true}";
using JsonDocument doc = JsonDocument.Parse(jsonText);JsonElement root = doc.RootElement;
string product = root.GetProperty("product").GetString();int price = root.GetProperty("price").GetInt32();bool inStock = root.GetProperty("inStock").GetBoolean();
Console.WriteLine($"{product}: {price} rub. (in stock: {inStock})");JsonDocument implements IDisposable, so be sure to use using to release resources.
2. The Classic Newtonsoft.Json Library (Json.NET)
Before the advent of System.Text.