Skip to content

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

@Ristovski

Description

@Ristovski

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...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions