Zechiax / Modrinth.Net

A Modrinth API wrapper for C#
https://zechiax.github.io/Modrinth.Net/
MIT License
12 stars 3 forks source link

Use System.Text.Json code gen support for trimming/NativeAOT #134

Open Ristovski opened 1 month ago

Ristovski commented 1 month ago

When using Modrinth.Net in a project that gets published with trimming (dotnet publish -p:PublishSingleFile=true -p:PublishTrimmed=true --self-contained) and/or NativeAOT, the following trim warnings are produced:

ILLink : Trim analysis warning IL2026: Modrinth.Http.Requester.<GetJsonAsync>d__13<T>.MoveNext():
    Using member 'System.Text.Json.JsonSerializer.DeserializeAsync<TValue>(Stream, JsonSerializerOptions, CancellationToken)'
    which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code.
    JSON serialization and deserialization might require types that cannot be statically analyzed.
    Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.
ILLink : Trim analysis warning IL2026: Modrinth.Http.Requester.<SendAsync>d__14.MoveNext():
    Using member 'System.Text.Json.JsonSerializer.DeserializeAsync<TValue>(Stream, JsonSerializerOptions, CancellationToken)'
    which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code.
    JSON serialization and deserialization might require types that cannot be statically analyzed.
    Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved. 

System.Text.Json code gen support should be used instead of the default reflection-based approach: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation?pivots=dotnet-8-0

This can be easily done by deriving from the JsonSerializerContext class, annotating it with [JsonSerializable(typeof(...))] and then passing the class to any serialization/deserialization method.

However, I am not sure how to easily handle the use of TValue generics...

Zechiax commented 3 weeks ago

That's a new one for me! I tried to solve it in the feature/trimming branch, but will have to look into it again later, as it did not work as expected.