c# - 使用 JSON.net,在基类上下文中使用时,如何防止序列化派生类的属性?

标签 c# serialization json.net

给定一个数据模型:

[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/

相关文章:

c# - 如何在转换为 json 时格式化对象中仅为字符串的属性?

c# - TypeScript 从不在 C# 中输入?

C# 如何很好地将 float 格式化为没有不必要的小数点 0 的字符串?

c# - 获取具有指定 ID 的行之后按字母顺序排列的行

c# - 我应该如何保存我的数据?

c# - 使用 Json.Net 反序列化时设置必填字段

c# - 如何在 HtmlHelper 扩展方法上获取 Controller 和操作的语法突出显示?

ios - 在 SWIFT (IOS) 中将 UIBezierPath 作为 Blob 存储到 SQLite

json - 将对象序列化为 json 产生双引号

c# - 使用 JSON.net 将枚举容器序列化为字符串