asp.net core 3.0 MVC JSON 全局配置 System.Text.Json(default) 1. startup配置代碼如下: 2. "官方API" Newtonsoft.Json 1. Install Package Microsoft.AspNetCore.Mvc.Newt ...
asp.net core 3.0 MVC JSON 全局配置
- System.Text.Json(default)
- startup配置代碼如下:
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
public void ConfigureServices(IServiceCollection services)
{
services.AddJsonOptions(options =>
{
//格式化日期時間格式
options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
//數據格式首字母小寫
//options.JsonSerializerOptions.PropertyNamingPolicy =JsonNamingPolicy.CamelCase;
//數據格式原樣輸出
options.JsonSerializerOptions.PropertyNamingPolicy = null;
//取消Unicode編碼
options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
//忽略空值
options.JsonSerializerOptions.IgnoreNullValues = true;
//允許額外符號
options.JsonSerializerOptions.AllowTrailingCommas = true;
//反序列化過程中屬性名稱是否使用不區分大小寫的比較
options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
});
}
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
public class DatetimeJsonConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
if (DateTime.TryParse(reader.GetString(), out DateTime date))
return date;
}
return reader.GetDateTime();
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
- Newtonsoft.Json
- Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.1.0
- startup配置代碼如下:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public void ConfigureServices(IServiceCollection services)
{
services.AddNewtonsoftJson(options =>
{
//設置時間格式
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
//忽略迴圈引用
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//數據格式首字母小寫
//options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
//數據格式按原樣輸出
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
//忽略空值
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
}