NetCore 统一处理 webapi 返回null 转为“”
程序员文章站
2024-02-05 20:00:58
数据库中部分表字段允许空值,则代码中实体类对应的字段类型为可空类型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)); });