有很多关于基于条件跳过Properties的信息,但我希望基于对象类中的条件跳过整个对象。如果可能的话,我想要一个包含在对象类中的解决方案。请记住,这是我正在序列化的myObj
的集合。
public class myObj
{
bool conditional;
ShouldSerialize()
{
return conditional;
}
}
或
public class myObj
{
[JsonCondition]
public bool conditional{get;}
}
甚至
[JsonCondition(typeof(MyConditionChecker))]
public class myObj
{
public bool conditional{get;}
}
class MyConditionChecker: JsonCondition
{
public override bool CanConvert(object sourceObj)
{
return (sourceObj as myObj).conditional;
}
}
我从你的评论中得到的是,你最好围绕Json创建自己的包装器来应用过滤。
public interface IConditionalSerializer
{
bool ShouldBeSerialized();
}
public static class FilteredSerializer
{
public static string SerializeConditional<T>(IEnumerable<T> input)
where T : IConiditionalSerializer
{
return JsonConvert.SerializeObject(input.Where(e => e.ShouldBeSerialized()));
}
}
public class Demo : IConditionalSerializer
{
public bool ShouldBeSerialized() => false;
}
您也可以用反射方法替换接口,但要记住性能损失。
public interface IConiditionChecker
{
bool ShouldBeSerialized(object instance);
}
public class ConditionAttribute : Attribute
{
public Type ConditionChecker { get; set; }
}
public static class FilteredSerializer
{
public static string SerializeConditional(IEnumerable<object> input)
{
var matches = (from entry in input
let att = entry.GetType().GetCustomAttribute<ConditionAttribute>()
let hasChecker = att != null && att.ConditionChecker != null
let checker = hasChecker ? (IConiditionChecker)Activator.CreateInstance(att.ConditionChecker) : null
where checker.ShouldBeSerialized(entry)
select entry);
return JsonConvert.SerializeObject(matches);
}
}
[Condition(ConditionChecker = typeof(SomeChecker))]
public class Demo
{
}
编辑:根据您的评论,您可以这样做。只需决定在where
-语句中使用选择加入还是选择退出。它必须是casted != null && casted.ShouldBeSerialized
或它目前所说的。
public interface IShouldBeSerialized
{
bool ShouldBeSerialized();
}
public static class FilteredSerializer
{
public static string SerializeConditional(IEnumerable<object> input)
{
var matches = (from entry in input
let casted = entry as IShouldBeSerialized
where casted == null || casted.ShouldBeSerialized()
select entry);
return JsonConvert.SerializeObject(matches);
}
}
public class Demo : IShouldBeSerialized
{
public bool ShouldBeSerialized()
{
return false;
}
}
如果您能够使用JSON.NET序列化程序,就不序列化集合中的特定项而言,您可以使主集合不可序列化,然后添加另一个进行序列化的筛选集合。
public class Manager
{
[JsonIgnore]
public Employee[] Employees { get; set; }
[JsonProperty("Employees")]
public Employee[] SerializableEmployees
{
get { return Employees.Where(e => e.Name != "Bob").ToArray(); }
set { Employees = value; }
}
}
或者,您可以用[JsonConverter]
属性标记您的类,并使用自定义转换器来检查您的条件。这里详细介绍了一种完全忽略类的类似方法。