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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free