Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set properties to exclude from serialization

Is it possible to programmatically set that you want to exclude a property from serialization?

Example:

  • When de-serializing, I want to load up an ID field
  • When serializing, I want to NOT output the ID field
like image 956
Paul Avatar asked Jun 10 '10 18:06

Paul


People also ask

How do you ignore property serializable?

In XML Serializing, you can use the [XmlIgnore] attribute (System. Xml. Serialization. XmlIgnoreAttribute) to ignore a property when serializing a class.

How to ignore property 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.

What attribute is used to prevent a public field from being serialized?

When using the BinaryFormatter or SoapFormatter classes to serialize an object, use the NonSerializedAttribute attribute to prevent a field from being serialized.


2 Answers

I believe there are three options here:

  1. Use XmlIgnore attribute. The downside is that you need to know in advance which properties you want the xmlserializer to ignore.

  2. Implement the IXmlSerializable interface. This gives you complete control on the output of XML, but you need to implement the read/write methods yourself.

  3. Implement the ICustomTypeDescriptor interface. I believe this will make your solution to work no matter what type of serialization you choose, but it is probably the lengthiest solution of all.

 

like image 109
Anax Avatar answered Sep 28 '22 12:09

Anax


It depends on serialization type. Here full example for doing this with BinaryFormatter:

You may use OnDeserializedAttribute:

[Serializable]
class SerializableEntity
{
  [OnDeserialized]
  private void OnDeserialized()
  {
    id = RetrieveId();
  }

  private int RetrievId() {}

  [NonSerialized]
  private int id;
}

And there is another way to do this using IDeserializationCallback:

[Serializable]
class SerializableEntity: IDeserializationCallback 
{
  void IDeserializationCallback.OnDeserialization(Object sender) 
  {
    id = RetrieveId();
  }

  private int RetrievId() {}

  [NonSerialized]
  private int id;
}

Also you may read great Jeffrey Richter's article about serialization: part 1 and part 2.

like image 44
Sergey Teplyakov Avatar answered Sep 28 '22 11:09

Sergey Teplyakov