Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to serialize some attribute in some condition

When using XML serialization to serialize a class, how to make some attribute be outputted conditionally. i.e. In some case, it output this attribute, in other cases, it does not.

like image 933
user496949 Avatar asked Dec 08 '10 10:12

user496949


People also ask

How do you avoid variables to serialize?

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 JsonIgnore C#?

Ignore individual properties 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. If no Condition is specified, this option is assumed.

How do you serialize a data set?

You can serialize a populated DataSet object to an XML file by executing the DataSet object's WriteXml method. You can serialize a populated DataSet object to an XML file by executing the DataSet object's WriteXml method.


2 Answers

You can create an additional property which is called MyPropertySpecified, which returns a boolean.
When this property returns true, the MyProperty property will be serialized. When it returns false, it will not be serialized.

Also, you'd want to decorate that property with the XmlIgnoreAttribute, so that this specific property is not serialized.

Example:

public class Person
{
    public string Name
    {
        get;
        set;
    }

    [XmlIgnore]
    public bool NameSpecified
    {
        get  { return Name != "secret"; }
    }
}
like image 126
Frederik Gheysels Avatar answered Sep 23 '22 00:09

Frederik Gheysels


While works and is a rather short solution, the propertyNameSpecified pattern has some drawbacks in my opinion (pollutes the interface of your class; relies on property names; introduces implicit behavior).

If you only need to implement a simple condition (e.g. don't serialize a default value), then the DefaultValue attribute is a better choice.

For example:

public class PurchaseOrder
{
    [DefaultValue("2002")]
    public string Year;
}

If Year has the value "2002", it will be omitted from the XML output.

like image 36
Tamás Szelei Avatar answered Sep 21 '22 00:09

Tamás Szelei