public class NullToEmptyStringResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return type.GetProperties()
.Select(p=>{
var jp = base.CreateProperty(p, memberSerialization);
jp.ValueProvider = new NullToEmptyStringValueProvider(p);
return jp;
}).ToList();
}
}
public class NullToEmptyStringValueProvider : IValueProvider
{
PropertyInfo _MemberInfo;
public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
{
_MemberInfo = memberInfo;
}
public object GetValue(object target)
{
object result = _MemberInfo.GetValue(target);
if (_MemberInfo.PropertyType == typeof(string) && result == null) result = "";
return result;
}
public void SetValue(object target, object value)
{
_MemberInfo.SetValue(target, value);
}
}
调用方式在Application_Start文件中配置:
var formatter = GlobalConfiguration.Configuration.Formatters;
formatter.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
formatter.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
//格式化Json中的时间格式
var timeConverter = new IsoDateTimeConverter
{
DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
};
formatter.JsonFormatter.SerializerSettings.Converters.Add(timeConverter);
formatter.JsonFormatter.SerializerSettings.ContractResolver = new NullToEmptyStringResolver();