首页 > Web开发 > 详细

ASP.NET Core学习之六 JSON全局配置

时间:2020-08-10 09:14:28      阅读:82      评论:0      收藏:0      [点我收藏+]

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);

ASP.NET Core学习之六 JSON全局配置

原文:https://www.cnblogs.com/xcsn/p/13467018.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!