.netcore webapi json返回值序列化null替换为空字符串
场景:数据库中部分表字段允许空值,则代码中实体类对应的字段类型为可空类型Nullable<>,如int?,DateTime?,null值字段序列化返回的值都为null,前端对应字段赋值需要做null值判断,随想到全局把null替换为""
网上找的方案都是重写了DefaultContractResolver,但是该方法只能解决string类型null→""的问题,对其他可空类型无效。
研究了下git 上Newtonsoft.Json和.netcore MVC的源码
最终使用自定义JsonOutputFormatter方式实现:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//过滤器
services.AddMvc(config =>
{
var settings = new JsonSerializerSettings();
settings.ContractResolver = new DefaultContractResolver();
//统一设置JsonResult中的日期格式
settings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
config.OutputFormatters.Insert(0, new MyJsonOutputFormatter(settings));
});
//services.AddMvc().AddJsonOptions(options =>
//{
// //options.SerializerSettings.ContractResolver = new SubstituteNullWithEmptyStringContractResolver();
// 统一设置JsonResult中的日期格式
// //options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
//});
services.AddMvcCore().AddApiExplorer();
}
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);
}
}