Home >Backend Development >C++ >How to Exclude Properties from JSON Serialization in C#?
How to exclude JSON serialization attributes in C#
When serializing an object to JSON, it is often necessary to exclude certain properties to reduce the size of the serialized data or to maintain privacy. This article explores two common methods for excluding JSON serialization of public properties.
Method 1: Use the [JsonIgnore] attribute
If you are using the popular Json.Net library, the [JsonIgnore] attribute provides a direct way to exclude properties. By annotating a property with this attribute, you can instruct the serializer to ignore it during both serialization and deserialization.
For example:
<code class="language-csharp">public class Car { // 包含在 JSON 中 public string Model { get; set; } public DateTime Year { get; set; } public List<string> Features { get; set; } // 排除 [JsonIgnore] public DateTime LastModified { get; set; } }</code>
Method 2: Use DataContract and DataMember properties
Alternatively, you can use the DataContract and DataMember properties provided by the System.Runtime.Serialization namespace. The DataContract attribute marks the class as serializable, and the DataMember attribute specifies the properties to include.
<code class="language-csharp">[DataContract] public class Computer { // 包含在 JSON 中 [DataMember] public string Name { get; set; } [DataMember] public decimal SalePrice { get; set; } // 排除 public string Manufacture { get; set; } public int StockCount { get; set; } public decimal WholeSalePrice { get; set; } public DateTime NextShipmentDate { get; set; } }</code>
Detailed explanation
Both methods work by manipulating the serialization process. The [JsonIgnore] attribute instructs the Json.Net serializer to skip annotated properties, while the DataMember attribute explicitly specifies which properties to serialize.
While the [JsonIgnore] attribute is easier to use, the DataContract and DataMember attributes provide more control over serialization and deserialization. They also allow you to control other aspects of serialization, such as the name of the property and the serialization format.
The above is the detailed content of How to Exclude Properties from JSON Serialization in C#?. For more information, please follow other related articles on the PHP Chinese website!