如何为System.Text.Json AOT保留特定内置类型?
针对List<Dictionary<string, int>>的AOT JSON序列化解决方案
针对内置集合类型在AOT环境下的JSON序列化问题,有以下几种直接可行的方案:
1. 显式定义JsonSerializerContext(官方推荐)
这是.NET官方针对AOT场景推荐的方式,通过源代码生成提前生成序列化所需的元数据。创建一个继承自JsonSerializerContext的部分类,并标记需要序列化的目标类型即可:
[JsonSourceGenerationOptions(WriteIndented = true)] [JsonSerializable(typeof(List<Dictionary<string, int>>))] public partial class MyJsonContext : JsonSerializerContext { }
使用时直接调用生成的上下文属性:
var myData = new List<Dictionary<string, int>> { new() { { "Count", 10 }, { "Value", 20 } }, new() { { "Count", 15 }, { "Value", 25 } } }; string json = JsonSerializer.Serialize(myData, MyJsonContext.Default.ListDictionaryStringInt);
这种方式会在编译期生成序列化代码,完全适配AOT环境,同时性能最优。
2. 手动创建JsonTypeInfo
如果不想生成上下文类,可以手动创建JsonTypeInfo实例,显式传入序列化所需的类型信息:
var serializerOptions = new JsonSerializerOptions(); var targetTypeInfo = JsonTypeInfo.Create(typeof(List<Dictionary<string, int>>), serializerOptions); var myData = new List<Dictionary<string, int>> { new() { { "Key", 1 } } }; string json = JsonSerializer.Serialize(myData, targetTypeInfo);
这种方式适合临时的、单个类型的序列化场景,无需额外的类定义。
3. 使用DynamicDependency特性保留元数据
如果不想修改序列化调用方式,可以通过[DynamicDependency]特性告诉AOT编译器保留目标类型的序列化相关元数据。需要注意标记所有嵌套的相关类型:
using System.Diagnostics.CodeAnalysis; [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(List<Dictionary<string, int>>))] [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(Dictionary<string, int>))] public string SerializeListDict(List<Dictionary<string, int>> data) { return JsonSerializer.Serialize(data); }
这种方式不需要修改序列化调用的代码,但需要确保所有涉及的嵌套类型都被标记,否则仍可能触发AOT错误。
内容的提问来源于stack exchange,提问作者Civ01
相关产品推荐
相关产品推荐

