在开发web api的时候 遇到一个要把string未赋值默认为null的情况改成默认为空字符串的需求
这种情况就需要自定义json序列话的 解析协议了
Newtonsoft.Json默认的解析协议是DefaultContractResolver
需要继承DefaultContractResolver 自定义解析协议了
public class NullableValuePRovider : IValueProvider { private readonly object _defaultValue; private readonly IValueProvider _underlyingValueProvider; public NullableValueProvider(MemberInfo memberInfo, Type underlyingType) { _underlyingValueProvider = new DynamicValueProvider(memberInfo); if (underlyingType != typeof(string)) { _defaultValue = Activator.CreateInstance(underlyingType); } else { _defaultValue = string.Empty; // 特殊处理 } } public void SetValue(object target, object value) { _underlyingValueProvider.SetValue(target, value); } public object GetValue(object target) { return _underlyingValueProvider.GetValue(target) ?? _defaultValue; } } public class SpecialContractResolver : DefaultContractResolver { protected override IValueProvider CreateMemberValueProvider(MemberInfo member) { if (member.MemberType == MemberTypes.Property) { var pi = (PropertyInfo)member; if (pi.PropertyType == typeof(string)) { return new NullableValueProvider(member, pi.PropertyType); } } else if (member.MemberType == MemberTypes.Field) { var fi = (FieldInfo)member; if (fi.FieldType == typeof(string)) { return new NullableValueProvider(member, fi.FieldType); } } return base.CreateMemberValueProvider(member); } }
参考
新闻热点
疑难解答