public class NullToEmptyStringResolver : DefaultContractResolver { /// /// 創建屬性 /// /// 類型 /// 序列化成員 /// protected override IList Creat... ...
public 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); } }