c# – 避免在域模型中使用JsonIgnore属性

前端之家收集整理的这篇文章主要介绍了c# – 避免在域模型中使用JsonIgnore属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个域模型组件与几个实体类.在另一个组件中,我有使用Json.NET序列化实现的实体存储库.我想在序列化期间忽略一些实体属性,所以直接的解决方案是使用JsonIgnore属性来装饰这些属性.但是,从原理上讲,我想在我的域模型中避免引用其他组件(包括Json.NET这样的第三方库).

我知道我可以创建一个定制的契约解析器,如here所述,但是很难概括什么序列化和什么不能在各个实体中序列化.通常我想忽略所有只读属性,但有例外,例如集合:

public List<Pixel> Pixels
{
    get { return this.Pixels; }
}

我也可以为每个实体创建一个专门的合同解析器,如here所述,但这似乎是一个高维护的解决方案,特别是对于许多实体.

理想的解决方案是,如果Json.NET支持.NET框架中的某些属性,但是我甚至找不到合适的候选项…

我想到在我的域模型中创建自己的自定义Ignore属性,并制作一个自定义契约解析器,它使用反射来检测此属性,并在序列化时忽略装饰属性.但是真的是给定问题的最佳解决方案吗?

解决方法

I believe by default that Json.net Respects DataContractAttribute.虽然您必须是包容性而不是排他性,但也意味着序列化可以更改为Microsoft二进制(或可能是xml),而不必重新设计您的域模型.

If a class has many properties and you only want to serialize a small subset of them then adding JsonIgnore to all the others will be tedious and error prone. The way to tackle this scenario is to add the DataContractAttribute to the class and DataMemberAttributes to the properties to serialize. This is opt-in serialization,only the properties you mark up with be serialized,compared to opt-out serialization using JsonIgnoreAttribute.

[DataContract]
public class Computer
{
  // included in JSON
  [DataMember]
  public string Name { get; set; }
  [DataMember]
  public decimal SalePrice { get; set; }

  // ignored
  public string Manufacture { get; set; }
  public int StockCount { get; set; }
  public decimal WholeSalePrice { get; set; }
  public DateTime NextShipmentDate { get; set; }
}
原文链接:https://www.f2er.com/csharp/95293.html

猜你在找的C#相关文章