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
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; }
}
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; }
}
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.