How to Serialize and Deserialize JSON in C#
JSON serialization and deserialization in C# has become remarkably straightforward with the System.Text.Json namespace, introduced in .NET Core 3.0 as a modern alternative to Newtonsoft.Json.
The JsonSerializer class provides static methods to convert objects to JSON strings (Serialize) and parse JSON strings back into objects (Deserialize).
For basic serialization, you can simply call JsonSerializer.Serialize(object)
on any object, and it will automatically convert public properties into their JSON representation.
Similarly, JsonSerializer.Deserialize<T>(jsonString)
converts JSON back into strongly-typed objects. The process becomes even more powerful when combined with custom attributes like [JsonPropertyName] to control property naming and [JsonIgnore] to exclude specific properties from serialization.
When working with more complex scenarios, you can customize the serialization process using JsonSerializerOptions.
This allows you to control various aspects such as case sensitivity, indentation, handling of null values, and custom converters. For example, setting PropertyNameCaseInsensitive = true
enables case-insensitive property matching during deserialization, while WriteIndented = true
produces formatted JSON output.
It's also worth noting that System.Text.Json is designed with performance in mind, offering better performance compared to Newtonsoft.Json for most scenarios.
Example
// Define a class to serialize
public class Person
{
public string Name { get; set; }
[JsonPropertyName("birth_date")]
public DateTime BirthDate { get; set; }
[JsonIgnore]
public int InternalId { get; set; }
}
// Serialization example
Person person = new Person
{
Name = "John Doe",
BirthDate = new DateTime(1990, 1, 1)
};
string json = JsonSerializer.Serialize(person);
// Deserialization example
Person deserializedPerson = JsonSerializer.Deserialize<Person>(json);
// Using JsonSerializerOptions
var options = new JsonSerializerOptions
{
WriteIndented = true,
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
string prettyJson = JsonSerializer.Serialize(person, options);
// Working with collections
List<Person> people = new List<Person> { person };
string jsonArray = JsonSerializer.Serialize(people);
List<Person> deserializedPeople = JsonSerializer.Deserialize<List<Person>>(jsonArray);