I have a DTO class which I Serialize
Json.Serialize(MyClass)
How can I exclude a public property of it?
(It has to be public, as I use it in my code somewhere else)
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.
JsonSerializationException(String, Exception) Initializes a new instance of the JsonSerializationException class with a specified error message and a reference to the inner exception that is the cause of this exception.
If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
If you are using Json.Net attribute [JsonIgnore]
will simply ignore the field/property while serializing or deserialising.
public class Car { // included in JSON public string Model { get; set; } public DateTime Year { get; set; } public List<string> Features { get; set; } // ignored [JsonIgnore] public DateTime LastModified { get; set; } }
Or you can use DataContract and DataMember attribute to selectively serialize/deserialize properties/fields.
[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; } }
Refer http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size for more details
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With