ASP.NET Core学习之六 JSON全局配置
Startup
全局配置Json序列化处理
1.忽略循环引用
2.long转string
//全局配置Json序列化处理
services.AddJsonOptions(options =>
{
//忽略循环引用
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.Converters.Add(new Common.LongConvert());//Long类型转换
//在这里日期类格式化处理是不起作用的
//不返回值为NULL的属性,甚用啊,数据要很严谨
//options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
数据处理
1.时间格式
2.string null转空
Startup
services.PostConfigure<MvcJsonOptions>(options =>
{
options.SerializerSettings.ContractResolver = new CustomContractResolver();
});
自定义转换
CustomContractResolver
/// <summary>
/// Json序列化转换器
/// </summary>
public class CustomContractResolver : AbpCamelCasePropertyNamesContractResolver
{
protected override void ModifyProperty(MemberInfo member, JsonProperty property)
{
if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?))
{
property.Converter = new AbpDateTimeConverter()
{ DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
}
else
{
base.ModifyProperty(member, property);
}
}
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();
}
}
/// <summary>
/// NULL转为空字符串
/// </summary>
public class NullToEmptyStringValueProvider : IValueProvider
{
PropertyInfo _MemberInfo;
public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
{
_MemberInfo = memberInfo;
}
public object GetValue(object target)
{
object result = _MemberInfo.GetValue(target);
if (result == null && _MemberInfo.PropertyType.FullName == "System.String") result = "";
return result;
}
public void SetValue(object target, object value)
{
_MemberInfo.SetValue(target, value);
}
}
json序列化小驼峰格式
属性名首字母为小写
var setting = new JsonSerializerSettings
{
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
};
var json = JsonConvert.SerializeObject(resp, Formatting.None, setting);