如何配置Azure Functions (V2)的JSON序列化器以支持循环引用?
解决Azure Functions中JSON序列化循环引用问题
刚好我之前也处理过类似的场景,你遇到的循环引用导致JSON序列化失败/截断的问题,在Azure Functions里可以通过配置序列化器来解决,下面分两种常用的序列化方案给你详细说明:
1. 沿用Newtonsoft.Json(和你ASP.NET的配置对齐)
如果你习惯用Newtonsoft.Json(也就是Json.NET),可以按以下方式配置:
全局配置(通过Startup类)
如果你的Function项目启用了依赖注入(需要先安装Microsoft.Azure.Functions.Extensions NuGet包),可以创建Startup.cs来全局设置序列化规则:
using Microsoft.Azure.Functions.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; [assembly: FunctionsStartup(typeof(YourProjectNamespace.Startup))] namespace YourProjectNamespace { public class Startup : FunctionsStartup { public override void Configure(IFunctionsHostBuilder builder) { // 配置Newtonsoft.Json的循环引用处理 builder.Services.AddMvcCore().AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize; options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects; }); } } }
这样配置后,所有返回JsonResult的Function都会自动应用这个规则,序列化时会生成带$id和$ref的JSON,避免循环引用导致的异常。
局部配置(针对单个Function)
如果不想全局修改,也可以在单个Function里手动序列化:
using Newtonsoft.Json; using Microsoft.AspNetCore.Mvc; public IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req) { var pp = new Person(); pp.Name = "TONY"; pp.Children.Add(new Person() { Parent = pp, Name = "ESTHER" }); // 自定义序列化设置 var jsonSettings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Serialize, PreserveReferencesHandling = PreserveReferencesHandling.Objects }; var serializedJson = JsonConvert.SerializeObject(pp, jsonSettings); return new ContentResult { Content = serializedJson, ContentType = "application/json", StatusCode = 200 }; }
2. 使用Azure Functions默认的System.Text.Json
如果你的项目用的是默认的System.Text.Json序列化器,配置方式更简洁:
全局配置(通过Startup类)
同样在Startup.cs里配置:
using Microsoft.Azure.Functions.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection; using System.Text.Json; [assembly: FunctionsStartup(typeof(YourProjectNamespace.Startup))] namespace YourProjectNamespace { public class Startup : FunctionsStartup { public override void Configure(IFunctionsHostBuilder builder) { builder.Services.AddMvcCore().AddJsonOptions(options => { // 启用循环引用保留 options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve; // 可选:格式化JSON输出,方便阅读 options.JsonSerializerOptions.WriteIndented = true; }); } } }
这种方式会让序列化器自动处理循环引用,生成符合规范的带有引用标记的JSON。
内容的提问来源于stack exchange,提问作者Tony
相关产品推荐
相关产品推荐

