数据库中部门表字段允许空值,则代码中实体类对应的字段类型为可空类型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));
- });
复制代码
来源:https://www.cnblogs.com/rtwo/archive/2019/09/24/11578753.html |