Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid serialization default values?

Tags:

c#

How should i mark properties, that they should not be serialize if they have default values? For example if i have boolean value it shoudl be serialized if is only set to true, the same with nullable value, if they are null i don't want to include them in my serialization file.

like image 888
kosnkov Avatar asked Feb 24 '12 11:02

kosnkov


2 Answers

Ok I found it myself. It is [DefaultValue(false)]. If I mark some property with this attr then it will be serialized only if is different than value in ().

System.ComponentModel.DefaultValueAttribute

like image 125
kosnkov Avatar answered Sep 26 '22 02:09

kosnkov


There is such thing as Specified property. I can't find msdn documentation on it but this article should be helpful. Basically you have to write something like this:

//this property would not be serialized if it contains String.Empty value
public string PropertyName   {   get; set;  }


[XmlIgnore]
public bool PropertyNameSpecified
{
    get  { return PropertyName != String.Empty; }
}
like image 24
Denis Palnitsky Avatar answered Sep 24 '22 02:09

Denis Palnitsky