Menu

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);
0
480

Related

When working with URLs in C#, encoding is essential to ensure that special characters (like spaces, ?, &, and =) don’t break the URL structure. The recommended way to encode a string for a URL is by using Uri.EscapeDataString(), which converts unsafe characters into their percent-encoded equivalents.

string rawText = "hello world!";
string encodedText = Uri.EscapeDataString(rawText);

Console.WriteLine(encodedText); // Output: hello%20world%21

This method encodes spaces as %20, making it ideal for query parameters.

For ASP.NET applications, you can also use HttpUtility.UrlEncode() (from System.Web), which encodes spaces as +:

using System.Web;

string encodedText = HttpUtility.UrlEncode("hello world!");
Console.WriteLine(encodedText); // Output: hello+world%21

For .NET Core and later, Uri.EscapeDataString() is the preferred choice.

26
264

String interpolation, introduced in C# 6.0, provides a more readable and concise way to format strings compared to traditional concatenation (+) or string.Format(). Instead of manually inserting variables or placeholders, you can use the $ symbol before a string to directly embed expressions inside brackets.

string name = "Walt";
string job = 'Software Engineer';

string message = $"Hello, my name is {name} and I am a {job}";
Console.WriteLine(message);

This would produce the final output of:

Hello, my name is Walt and I am a Software Engineer

String interpolation can also be chained together into a multiline string (@) for even cleaner more concise results:

string name = "Walt";
string html = $@"
    <div>
        <h1>Welcome, {name}!</h1>
    </div>";
36
125

Reading a file line by line is useful when handling large files without loading everything into memory at once.

✅ Best Practice: Use File.ReadLines() which is more memory efficient.

Example

foreach (string line in File.ReadLines("file.txt"))
{
    Console.WriteLine(line);
}

Why use ReadLines()?

Reads one line at a time, reducing overall memory usage. Ideal for large files (e.g., logs, CSVs).

Alternative: Use StreamReader (More Control)

For scenarios where you need custom processing while reading the contents of the file:

using (StreamReader reader = new StreamReader("file.txt"))
{
    string? line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

Why use StreamReader?

Lets you handle exceptions, encoding, and buffering. Supports custom processing (e.g., search for a keyword while reading).

When to Use ReadAllLines()? If you need all lines at once, use:

string[] lines = File.ReadAllLines("file.txt");

Caution: Loads the entire file into memory—avoid for large files!

3
224