我有一个类似的类:
class Test
{
public object Obj { get; set; }
}
有时,Obj
具有不可隔离类型的值,例如:byte[]
或SqlDataReader
。
我尝试制作一个自定义的ContractResolver
以忽略值类型为 byte[]
时。但它行不通:属性类型仍然是Object
,而不是byte[]
。
public class AutoIgnoreComplexTypesContractResolver : DefaultContractResolver
{
private static readonly List<Type> IgnoredTypes = new List<Type>()
{
typeof(byte[]),
typeof(SqlDataReader)
};
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
var propertyType = property.PropertyType.GetUnderlyingType();
if (IgnoredTypes.Contains(propertyType))
{
property.ShouldSerialize = instance => false;
}
else
{
property.ShouldSerialize = instance => true;
}
return property;
}
}
您能帮我获得实际价值类型并忽略它吗?
property.PropertyType
将返回该属性的声明(编译时)类型,该类型始终在此处 object
。如果要根据属性值的实际运行时类型进行序列化的决定,则需要使用反射从instance
获取值,然后检查其类型。
反试试:
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.PropertyType == typeof(object))
{
property.ShouldSerialize = instance =>
{
PropertyInfo pi = member as PropertyInfo;
object propertyValue = (pi != null) ? pi.GetValue(instance) : null;
return propertyValue != null && !IgnoredTypes.Contains(propertyValue.GetType());
};
}
else if (IgnoredTypes.Contains(property.PropertyType))
{
property.ShouldSerialize = instance => false;
}
return property;
}
小提琴:https://dotnetfiddle.net/2a2kmh