Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude property from Json Serialization

Tags:

json

c#

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)

like image 862
Elad Benda Avatar asked Apr 16 '12 06:04

Elad Benda


People also ask

How do I ignore properties in JSON?

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.

How can you prevent a property from being serialized?

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.

What is a JSON serialization exception?

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.

How do you tell Jackson to ignore a field during serialization?

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.


1 Answers

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

like image 80
JC Raja Avatar answered Sep 20 '22 14:09

JC Raja