加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:33:11 所属栏目:百科 来源:网络整理
导读:我有一个域模型组件与几个实体类.在另一个组件中,我有使用Json.NET序列化实现的实体存储库.我想在序列化期间忽略一些实体属性,所以直接的解决方案是使用JsonIgnore属性来装饰这些属性.但是,从原理上讲,我想在我的域模型中避免引用其他组件(包括Json.NET这样
我有一个域模型组件与几个实体类.在另一个组件中,我有使用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; }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读