给定一个数据模型:
[DataContract]
public class Parent
{
[DataMember]
public IEnumerable<ChildId> Children { get; set; }
}
[DataContract]
public class ChildId
{
[DataMember]
public string Id { get; set; }
}
[DataContract]
public class ChildDetail : ChildId
{
[DataMember]
public string Name { get; set; }
}
出于实现方便的原因,有时 Parent
上的 ChildId
对象实际上是 ChildDetail
对象。当我使用 JSON.net 序列化 Parent
时,它们会与所有 ChildDetail
属性一起写出。
有什么方法可以指示 JSON.net(或任何其他 JSON 序列化程序,我对项目的了解还不够深入,无法 promise )在序列化为基类时忽略派生类属性?
编辑:重要的是,当我直接序列化派生类时,我能够生成所有属性。我只想抑制 Parent
对象中的多态性。
最佳答案
我使用自定义 Contract Resolver限制要序列化的属性。这可能会为您指明正确的方向。
例如
/// <summary>
/// json.net serializes ALL properties of a class by default
/// this class will tell json.net to only serialize properties if they MATCH
/// the list of valid columns passed through the querystring to criteria object
/// </summary>
public class CriteriaContractResolver<T> : DefaultContractResolver
{
List<string> _properties;
public CriteriaContractResolver(List<string> properties)
{
_properties = properties
}
protected override IList<JsonProperty> CreateProperties(
JsonObjectContract contract)
{
IList<JsonProperty> filtered = new List<JsonProperty>();
foreach (JsonProperty p in base.CreateProperties(contract))
if(_properties.Contains(p.PropertyName))
filtered.Add(p);
return filtered;
}
}
在重写 IList 函数中,您可以使用反射来填充可能仅包含父属性的列表。
契约(Contract)解析器应用于您的 json.net 序列化程序。此示例来自 asp.net mvc 应用程序。
JsonNetResult result = new JsonNetResult();
result.Formatting = Formatting.Indented;
result.SerializerSettings.ContractResolver =
new CriteriaContractResolver<T>(Criteria);
关于c# - 使用 JSON.net,在基类上下文中使用时,如何防止序列化派生类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5872855/