Indicate how to Serialize my object, if it is in the list

I have a somewhat complex class that may or may not contain a list of elements of the same type

Class Items { List<Items> SubItems ... } 

The class itself is serializable, however, it is a huge waste of space for serializing objects in the list, since they are serialized and added to the database before being included in the list.

Is it possible to indicate that the list should be represented as a list of integers when it is serialized?

Note. These integers will represent the primary keys of the rows in which the serialized object is located.

+6
source share
3 answers

Is it possible to indicate that a list should be submitted? how is a list of integers when serializing it?

Yeah. There are two main options:

1) Add an ISerializable -Interface where you can control how the object will be serialized / deserialized.

OR

2) Declare your list as [NonSerialized] , and also manage a private user list that contains your primary keys. However, you will have to implement the logic for loading / storing Integer-List on your own.

If your class for serialization is quite large, I would recommend you a second approach, because in another case you will have to manually serialize / deserialize each property.

+1
source

To indicate how an object is serialized, you need to implement ISerializable and provide an implementation for GetObjectData

 public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { } 

There is a simple example on this MSDN page:

http://msdn.microsoft.com/en-us/library/ms973893.aspx

+1
source

If you want to save space, you can use the DataContractSerializer to achieve this. It has a preserveObjectReference parameter. Which does not duplicate the same object, but only stores referenceId.
More here

+1
source

Source: https://habr.com/ru/post/951063/


All Articles