DEV Community

Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - System.Text.Json Source Generators

C# introduced a feature in .NET 6 that significantly improves the performance of JSON serialization and deserialization - System.Text.Json source generators. This feature allows for compile-time generation of serializers for your data models, reducing the runtime overhead typically associated with reflection in JSON processing.

Here’s how to use System.Text.Json source generators:

  1. Setup Your Project:
    Ensure your project targets .NET 6 or later. You need to install the System.Text.Json NuGet package if it's not already included.

  2. Declare Partial Serializer Context:
    Create a partial class that inherits from JsonSerializerContext and use the [JsonSerializable] attribute to specify which models you want to generate serializers for.

  3. Use Generated Serializers:
    When serializing or deserializing, use the JsonSerializer methods that take your generated context as a parameter.

Example:

using System.Text.Json;
using System.Text.Json.Serialization;

[JsonSerializable(typeof(WeatherForecast))]
public partial class MyJsonSerializerContext : JsonSerializerContext
{
}

public class WeatherForecast
{
    public DateTime Date { get; set; }
    public int TemperatureCelsius { get; set; }
    public string? Summary { get; set; }
}

public static void Main()
{
    var forecast = new WeatherForecast
    {
        Date = DateTime.Now,
        TemperatureCelsius = 25,
        Summary = "Sunny"
    };

    string jsonString = JsonSerializer.Serialize(forecast, MyJsonSerializerContext.Default.WeatherForecast);
    var deserialized = JsonSerializer.Deserialize<WeatherForecast>(jsonString, MyJsonSerializerContext.Default.WeatherForecast);

    Console.WriteLine(jsonString);
}
Enter fullscreen mode Exit fullscreen mode

In this example, a JsonSerializable attribute is used to generate a serializer for the WeatherForecast class. By using the generated context in serialization and deserialization, the process becomes more efficient as it avoids the use of reflection at runtime.

System.Text.Json source generators are a powerful way to optimize JSON operations in .NET applications, particularly beneficial for high-performance scenarios like web services and applications dealing with large amounts of JSON data.

Top comments (0)