其他分享
首页 > 其他分享> > NetCore 统一处理 webapi 返回null 转为“”

NetCore 统一处理 webapi 返回null 转为“”

作者:互联网

数据库中部分表字段允许空值,则代码中实体类对应的字段类型为可空类型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));
            });

标签:webapi,NetCore,writer,SerializerSettings,new,null,public,settings
来源: https://www.cnblogs.com/rtwo/p/11578753.html