Search⌘ K
AI Features

Working with JSON

Explore how to work with JSON data in C# using the System.Text.Json namespace. Learn serialization and deserialization of objects, reading and writing JSON files asynchronously, and customizing output formatting to handle data effectively in .NET applications.

JSON (JavaScript Object Notation) is the industry standard format for data exchange, configuration files, and web APIs. It is a lightweight, text-based format that is easy for humans to read and write, and easy for machines to parse and generate.

Modern .NET provides the System.Text.Json namespace. This built-in library delivers high-performance JSON manipulation without relying on third-party packages. The two primary operations we perform with JSON are serialization and deserialization.

Serialization (C# object to JSON)

Serialization is the process of converting a .NET object (like a class or struct) into a JSON string. We use the JsonSerializer.Serialize method to convert a C# object into a JSON string.

C# 14.0
using System.Text.Json;
var course = new Course { Title = ".NET Fundamentals", Author = "John Doe", DurationInHours = 5 };
string jsonString = JsonSerializer.Serialize(course);
Console.WriteLine(jsonString);
public class Course
{
public string Title { get; set; } = string.Empty;
public string Author { get; set; } = string.Empty;
public int DurationInHours { get; set; }
}
  • Line 1: We import the System.Text.Json namespace to access the serialization ...