DEV Community

artydev
artydev

Posted on

.Net JSON serialization AOT compatible

Standart way of serializing use reflections, which is not compatible with AOT.

A solution is to use System.Text.Json source generator Try the new System.Text.Json source generator

From Nick Chapsas:
40% faster JSON serialization with Source Generators in .NET 6

In French
Tu sérialises mal tes objets en C#

Here is a console demo :

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

namespace json
{
    public class Person
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }

    [JsonSerializable(typeof(Person), GenerationMode = JsonSourceGenerationMode.Metadata)]
    public  partial class MyJsonContext : JsonSerializerContext
    { 
    }

    internal class Program
    {
        static void Main()
        {
            var person = new Person { Id = 1, Name = "Alice" };

            var context = new MyJsonContext();

            var personserialized = JsonSerializer.Serialize(person, context.Person);
            var persondeserialized = JsonSerializer.Deserialize<Person>(personserialized, context.Person);

            Console.WriteLine(
                $"\nSerialized : {personserialized}\n" +
                $"\nDeserialized : Id : {persondeserialized.Id}, Name : {persondeserialized.Name}"
            );
            Console.ReadLine();
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Here the publication configuration :

Image description

You can reduce the executable size usingupx

Image description

Top comments (0)