services.AddControllersWithViews().AddNewtonsoftJson(options =>
{
//设置序列化时间格式
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
options.SerializerSettings.ContractResolver = new NullToEmptyStringResolver();
});
public class NullToEmptyStringResolver : DefaultContractResolver
{
protected override JsonConverter ResolveContractConverter(Type objectType)
{
if (objectType == typeof(long))
{
return new JsonConverterLong();
}
if (objectType == typeof(int))
{
return new JsonConverterInt();
}
if (objectType == typeof(decimal))
{
return new JsonConverterDecimal();
}
if (objectType == typeof(double))
{
return new JsonConverterDouble();
}
return base.ResolveContractConverter(objectType);
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return type.GetProperties().Select(c =>
{
var jsonProperty = base.CreateProperty(c, memberSerialization);
jsonProperty.ValueProvider = new NullToEmptyStringValueProvider(c);
return jsonProperty;
}).ToList();
}
}
public class NullToEmptyStringValueProvider : IValueProvider
{
private readonly PropertyInfo _memberInfo;
public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
{
_memberInfo = memberInfo;
}
public object GetValue(object target)
{
var result = _memberInfo.GetValue(target);
if (_memberInfo.PropertyType == typeof(string) && result == null)
result = string.Empty;
return result;
}
public void SetValue(object target, object value)
{
_memberInfo.SetValue(target, value);
}
}
标签:Core,return,typeof,new,memberInfo,Net,Null,public,objectType
From: https://www.cnblogs.com/kkbk/p/17753726.html