如何通过JsonSourceGenerationOptions设置引用处理忽略循环?重写选项报错怎么办
解决Json源生成中设置忽略循环引用的问题
一、通过JsonSourceGenerationOptionsAttribute直接设置
在.NET 7及更高版本中,JsonSourceGenerationOptionsAttribute已新增ReferenceHandler属性,可直接在特性中配置忽略循环引用:
[JsonSourceGenerationOptions(WriteIndented = true, ReferenceHandler = ReferenceHandler.IgnoreCycles)] [JsonSerializable(typeof(WeatherForecast))] internal partial class SourceGenerationContext : JsonSerializerContext { }
如果你的项目基于.NET 6或更早版本,该属性不存在,需使用下方替代方法。
二、其他覆盖默认选项的方式
你尝试重写GeneratedSerializerOptions报错,是因为源生成器已自动生成该属性的实现,无法在部分类中重复定义。可通过以下两种方式覆盖默认选项:
1. 创建Context实例时传入自定义选项
基于源生成的默认选项,创建新的JsonSerializerOptions实例并修改配置,再传入Context构造函数:
// 基于默认选项创建自定义配置 var customOptions = new JsonSerializerOptions(SourceGenerationContext.Default.Options) { ReferenceHandler = ReferenceHandler.IgnoreCycles, WriteIndented = true // 保留原有缩进设置,或按需修改 }; // 使用自定义选项初始化Context var context = new SourceGenerationContext(customOptions); // 执行序列化 var json = JsonSerializer.Serialize(weatherForecastInstance, context.WeatherForecast);
2. 在Context类中添加静态属性封装自定义配置
在部分类中添加静态属性,返回预配置好的Context实例,方便全局复用:
[JsonSourceGenerationOptions(WriteIndented = true)] [JsonSerializable(typeof(WeatherForecast))] internal partial class SourceGenerationContext : JsonSerializerContext { // 封装带忽略循环引用的Context实例 public static SourceGenerationContext IgnoreCyclesContext => new SourceGenerationContext( new JsonSerializerOptions(Default.Options) { ReferenceHandler = ReferenceHandler.IgnoreCycles }); } // 使用方式 var json = JsonSerializer.Serialize(weatherForecastInstance, SourceGenerationContext.IgnoreCyclesContext.WeatherForecast);
内容的提问来源于stack exchange,提问作者user246392
相关产品推荐
相关产品推荐

