JSON (JavaScript Object Notation) is a lightweight data interchange format widely used in modern web applications. C# provides robust support for working with JSON data, making it easy to serialize and deserialize objects, as well as parse and manipulate JSON structures.
C# offers multiple ways to handle JSON data. The most common approaches involve using the built-in System.Text.Json
namespace or third-party libraries like Newtonsoft.Json (Json.NET).
Introduced in .NET Core 3.0, System.Text.Json
provides high-performance, standards-compliant JSON handling capabilities.
To convert a C# object to JSON:
using System.Text.Json;
var person = new { Name = "John Doe", Age = 30 };
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine(jsonString);
// Output: {"Name":"John Doe","Age":30}
To parse JSON into a C# object:
string jsonString = @"{"Name":"Jane Smith","Age":25}";
var person = JsonSerializer.Deserialize<Person>(jsonString);
Console.WriteLine($"{person.Name} is {person.Age} years old.");
// Output: Jane Smith is 25 years old.
Json.NET is a popular third-party library that offers additional features and flexibility when working with JSON in C#.
using Newtonsoft.Json;
var person = new { Name = "Alice", Age = 28 };
string jsonString = JsonConvert.SerializeObject(person);
Console.WriteLine(jsonString);
// Output: {"Name":"Alice","Age":28}
string jsonString = @"{"Name":"Bob","Age":35}";
var person = JsonConvert.DeserializeObject<Person>(jsonString);
Console.WriteLine($"{person.Name} is {person.Age} years old.");
// Output: Bob is 35 years old.
System.Text.Json
and Json.NET based on your project requirements and performance needs.[JsonPropertyName]
or [JsonProperty]
to control property naming during serialization.JsonDocument
for parsing and querying JSON data without creating strongly-typed objects.By mastering JSON handling in C#, developers can efficiently work with data in modern web applications, APIs, and services. Whether you're building RESTful APIs with JSON or integrating with external services, understanding JSON in C# is crucial for effective data interchange.