Avoid using the JsonIgnore attribute in a domain model

后端 未结 3 1779
醉梦人生
醉梦人生 2020-12-17 18:35

I have a domain model component with several entity classes. In another component i have entity repositories implemented using Json.NET serialization. I want to ignore some

相关标签:
3条回答
  • 2020-12-17 19:04

    The Json serializer also supports opt-in serialization

    [JsonObject(MemberSerialization.OptIn)]
    public class File
    {
      // excluded from serialization
      // does not have JsonPropertyAttribute
      public Guid Id { get; set; }
    
      [JsonProperty]
      public string Name { get; set; }
    
      [JsonProperty]
      public int Size { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-17 19:07

    I believe by default that Json.net Respects the DataContractAttribute. Although you have to be inclusive instead of exclusive, it also means that the serialization can change to Microsofts Binary (or maybe xml) and not have to redesign your domain models.

    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; }
    }
    
    0 讨论(0)
  • 2020-12-17 19:25

    You might consider using something like a View Model to control which properties of your entity model are serialized. I haven't used it myself, but looked into using it for a project of mine, but AutoMapper might be something to look into to decouple the entity model from your serialized model.

    0 讨论(0)
提交回复
热议问题