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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay