Net Core 下 Newtonsoft.Json 转换字符串 null 替换成string.Empty
Posted lonelyxmas
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Net Core 下 Newtonsoft.Json 转换字符串 null 替换成string.Empty相关的知识,希望对你有一定的参考价值。
原文:Net Core 下 Newtonsoft.Json 转换字符串 null 替换成string.Emptypublic class NullToEmptyStringResolver : DefaultContractResolver { /// <summary> /// 创建属性 /// </summary> /// <param name="type">类型</param> /// <param name="memberSerialization">序列化成员</param> /// <returns></returns> protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { return type.GetProperties() .Select(x => { var property = CreateProperty(x, memberSerialization); property.ValueProvider = new NullToEmptyStringValueProvider(x); return property; }).ToList(); } /// <inheritdoc /> /// <summary> /// 小写 /// </summary> /// <param name="propertyName"></param> /// <returns></returns> protected override string ResolvePropertyName(string propertyName) { return propertyName.ToLower(); } }
public class NullToEmptyStringValueProvider : IValueProvider { private readonly PropertyInfo _memberInfo; /// <summary> /// 构造函数 /// </summary> /// <param name="memberInfo"></param> public NullToEmptyStringValueProvider(PropertyInfo memberInfo) { _memberInfo = memberInfo; } /// <inheritdoc /> /// <summary> /// 获取Value /// </summary> /// <param name="target"></param> /// <returns></returns> public object GetValue(object target) { var result = _memberInfo.GetValue(target); if (_memberInfo.PropertyType == typeof(string) && result == Convert.DBNull) { result = string.Empty; } return result; } /// <inheritdoc /> /// <summary> /// 设置Value /// </summary> /// <param name="target"></param> /// <param name="value"></param> public void SetValue(object target, object value) { _memberInfo.SetValue(target, value); } }
以上是关于Net Core 下 Newtonsoft.Json 转换字符串 null 替换成string.Empty的主要内容,如果未能解决你的问题,请参考以下文章
[Asp.Net Core]Asp.Net Core与配置系统的集成
[Asp.Net Core]Asp.Net Core与配置系统的集成
[Asp.Net Core]Asp.Net Core与配置系统的集成
在 asp.net core vs2015 update2 情况况下创建 asp.net core web application 的问题