March 2021
One of the common problems encountered when serializing .NET objects to JSON or XML is that the JSON/XML ends up containing a lot of unwanted properties and values. To solve the issue of unwanted JSON/XML, xsd2code has a range of built-in options to fine-tune what gets written from a serialized object.
For XML and/or JSON
Here is a summary table of how the ShouldSerialize [PropertyName] methods will inform the serializer to ignore the property :
Type | Ignored if |
---|---|
Collection | is null or empty |
ComplexType | is null |
string | is null or empty |
int, float, double | if value is equal to default type valueand the value has not been explicitly assigned |
Nullable | has no value |
Enum | if value is equal to default type valueand the value has not been explicitly assigned. |
Sample of class with SouldSerialize methods
public partial class Product : EntityBase<Product> { #region Private fields private bool _shouldSerializeqty; [EditorBrowsable(EditorBrowsableState.Never)] private string _sKU; [EditorBrowsable(EditorBrowsableState.Never)] private string _name; [EditorBrowsable(EditorBrowsableState.Never)] private int _qty; #endregion [XmlElement(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] [Newtonsoft.Json.JsonPropertyAttribute("SKU")] public string SKU { get { return _sKU; } set { if ((_sKU == value)) { return; } if (((_sKU == null) || (_sKU.Equals(value) != true))) { _sKU = value; OnPropertyChanged("SKU"); } } } [XmlElement(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] [Newtonsoft.Json.JsonPropertyAttribute("Name")] public string Name { get { return _name; } set { if ((_name == value)) { return; } if (((_name == null) || (_name.Equals(value) != true))) { _name = value; OnPropertyChanged("Name"); } } } [XmlElement(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] [Newtonsoft.Json.JsonPropertyAttribute("qty")] public int qty { get { return _qty; } set { if ((_qty.Equals(value) != true)) { _qty = value; OnPropertyChanged("qty"); } _shouldSerializeqty = true; } } /// <summary> /// Test whether qty should be serialized /// </summary> public virtual bool ShouldSerializeqty() { if (_shouldSerializeqty) { return true; } return (_qty != default(int)); } /// <summary> /// Test whether SKU should be serialized /// </summary> public virtual bool ShouldSerializeSKU() { return !string.IsNullOrEmpty(SKU); } /// <summary> /// Test whether Name should be serialized /// </summary> public virtual bool ShouldSerializeName() { return !string.IsNullOrEmpty(Name); } }
You've minified your data ! The environment thanks you, if the size of your files is important consider the MessagePack format also handled by Xsd2code++ it is the smallest of all formats in our tool.