NET 8 – How to use JsonStringEnumConverter with native AOT
JsonStringEnumConverter is not compatible with native AOT. To fix that, NET 8 introduces a new converter type JsonStringEnumConverter<TEnum> that is compatible with native AOT.
To use the new type, simply annotate your types as follows:
[JsonConverter(typeof(JsonStringEnumConverter<MyEnum>))]
public enum MyEnum { Foo, Bar }
[JsonSerializable(typeof(MyEnum))]
public partial class MyJsonSerializerContext : JsonSerializerContext { }
Code language: C# (cs)
Keep in mind: enum deserialization is case insensitive, while serialization can be cusomized via JsonNamingPolicy.
What happens if you try to use JsonStringEnumConverter and NativeAOT?
The first warning sign you will see is during compilation, where you will get a warning that:
Using member ‘System.Text.Json.Serialization.JsonStringEnumConverter.JsonStringEnumConverter()’ 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.
Then, when running the compiled code, you will get a runtime exception:
System.Reflection.MissingMetadataException: ‘System.Text.Json.Serialization.Converters.EnumConverter<MyEnum>’ is missing metadata.