.net core webapi 返回 日期格式 帕斯卡 驼峰 命名 忽略循环嵌套
nuget
Microsoft.AspNetCore.Mvc.NewtonsoftJson
builder.Services.AddControllers()
.AddNewtonsoftJson(options => {
//返回驼峰
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
/ //返回帕斯卡
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
//返回时间格式
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
//忽略循环嵌套
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
如果使用的是 ASP.NET Core 中的 Json.NET,可以将 Json.NET 配置为忽略在对象图中找到的循环。此配置是通过 Startup.cs
中的 ConfigureServices(...)
方法完成的。
public void ConfigureServices(IServiceCollection services) { ... services.AddMvc() .AddJsonOptions(
//忽略循环嵌套 options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); ... }
如果使用 System.Text.Json,可按如下所示对其进行配置。
public void ConfigureServices(IServiceCollection services) { ... services.AddControllers() .AddJsonOptions(options => {
//返回帕斯卡
options.JsonSerializerOptions.PropertyNamingPolicy = null;
//忽略循环嵌套
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
//返回时间格式
options.JsonSerializerOptions.Converters.Add(new CustomDateTimeConverter());
}); ... }
public class CustomDateTimeConverter : JsonConverter<DateTime> { private const string _dateFormat = "yyyy-MM-dd HH:mm:ss"; public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => DateTime.Parse(reader.GetString()); public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString(_dateFormat)); }
另一种替代方法是忽略导致 JSON 序列化循环的导航属性。 如果使用 Json.NET,可以使用 [JsonIgnore]
特性修饰其中一个导航属性,该特性指示 Json.NET 在序列化时不遍历该导航属性。 对于 System.Text.Json,可以使用 System.Text.Json.Serialization
命名空间中的 [JsonIgnore]
特性来实现相同的效果。
参考
关联数据和序列化 - EF Core | Microsoft Learn
Asp .Net Core 系列:Asp .Net Core 集成 Newtonsoft.Json_.net core addnewtonsoftjson-CSDN博客