Search code examples
c#.net-core.net-7.0system.text.jsonnative-aot

Can't compile with Native AOT about JsonSerializer.Deserialize


The framework I am using is .Net7.

Here is my code:

var Options=new JsonSerializerOptions()
{
    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(UnicodeRanges.All)
};
List<ThemeModel> ThemeList = JsonSerializer.Deserialize<List<ThemeModel>>(ThemeString, Options)??new List<ThemeModel>();

It works well when debugging or compiling without AOT.

When compiling with AOT, the output reports the error below:

1>,D:\Test\Theme.cs(38,30,38,104): warning IL3050: Using member 'System.Text.Json.JsonSerializer.Deserialize(String, Type, JsonSerializerOptions)' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.
1>,D:\Test\Theme.cs(38,30,38,104): warning IL2026: Using member 'System.Text.Json.JsonSerializer.Deserialize(String, Type, JsonSerializerOptions)' 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.

What's wrong with my code? And how can I compile the JsonSerializer.Deserialize with NativeAOT?


After using source generation in my project:

public class ThemeModel
{
    public string ThemeKey { get; set; } = "";

    public enum ThemeValueTypeEnum { LinearGradientBrush, SolidColorBrush, SVGStyle, ImageStyle }
    public ThemeValueTypeEnum ThemeValueType { get; set; }
    public string ThemeValue { get; set; } = "";
}

[JsonSerializable(typeof(ThemeModel))]
[JsonSerializable(typeof(string))]
[JsonSerializable(typeof(ThemeValueTypeEnum))]        
internal partial class ThemeModelSourceGenerationContext : JsonSerializerContext
{
}

public void LoadTheme(string ThemeString)
{
    var Options = new JsonSerializerOptions()
    {
        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(UnicodeRanges.All),
        TypeInfoResolver = ThemeModelSourceGenerationContext.Default
    };
    List<ThemeModel> ThemeList = JsonSerializer.Deserialize<List<ThemeModel>>(ThemeString, Options)??new List<ThemeModel>();
}

It still reports the same error.


Solution

  • When using JsonSerializerOptions with the TypeInfoResolver property, it's a false-positive warning and can be ignored.

    This has been confirmed by a Microsoft engineer: https://github.com/dotnet/runtime/issues/51544#issuecomment-1516232559