資料庫中部分表欄位允許空值,則代碼中實體類對應的欄位類型為可空類型Nullable,如int?,DateTime?,null值欄位序列化返回的值都為null,前端對應欄位賦值需要做null值判斷,隨想到全局把null替換為"" 網上找的方案都是重寫了DefaultContractResolver,但... ...
資料庫中部分表欄位允許空值,則代碼中實體類對應的欄位類型為可空類型Nullable<>,如int?,DateTime?,null值欄位序列化返回的值都為null,前端對應欄位賦值需要做null值判斷,隨想到全局把null替換為""
網上找的方案都是重寫了DefaultContractResolver,但是該方法只能解決string類型null→""的問題,對其他可空類型無效。
研究了下git 上Newtonsoft.Json和.netcore MVC的源碼
最終使用自定義JsonOutputFormatter方式實現:
public class MyJsonOutputFormatter : JsonOutputFormatter { public MyJsonOutputFormatter(JsonSerializerSettings serializerSettings) : base(serializerSettings, ArrayPool<char>.Shared) { } public new JsonSerializerSettings SerializerSettings => base.SerializerSettings; protected override JsonWriter CreateJsonWriter(TextWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } var jsonWriter = new NullJsonWriter(writer) { ArrayPool = new JsonArrayPool<char>(ArrayPool<char>.Shared), CloseOutput = false, AutoCompleteOnClose = false }; return jsonWriter; } } public class NullJsonWriter : JsonTextWriter { public NullJsonWriter(TextWriter textWriter):base(textWriter) { } public override void WriteNull() { this.WriteValue(String.Empty); } }
在 Startup 代碼裡面 修改
//services.AddMvc().AddJsonOptions(option => { // //配置大小寫問題,預設是首字母小寫,該配置根據項目需要更改 // //option.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); // //配置序列化時時間格式為時間戳 // //option.SerializerSettings.ContractResolver = new NullToEmptyStringResolver(); // option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; //}); services.AddMvc(config => { var settings = new JsonSerializerSettings(); //設置首字母小寫,如果不需要 則改為 DefaultContractResolver settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //統一設置JsonResult中的日期格式 settings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; config.OutputFormatters.Insert(0, new MyJsonOutputFormatter(settings)); });