Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling order of serialization in C#

I'm using an XmlSerializer to serialize an object and write it to a file. I've had quite a bit of success with the serializer doing what I want it to do in terms of nesting elements and what is serialized as elements vs attributes. Unfortunately, I've run into a problem where I need one member of a class to serialize before another. Elsewhere it's worked for me that whatever is declared first gets serialized first, but in this instance I'm not having so much success with that. Is there any way to manually control the order in which things are serialized?

like image 230
Zann Anderson Avatar asked Jul 30 '10 16:07

Zann Anderson


People also ask

What are the types of serialization?

There are three types of serialization in . Net : Binary Serialization, SOAP Serialization and XML Serialization.

What is serialization in C?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

How do I prevent some data from getting serialized?

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.

How many types of Serialisation that are commonly used?

There are three types of serialization: binary serialization, SOAP (Simple Object Access Protocol or Service Oriented Architecture Protocol) serialization, and XML (Extensible Markup Language) serialization.


2 Answers

[XmlElementAttribute(Order = 1)] 
public int Field1 {...} 

[XmlElementAttribute(Order = 2)] 
public int Field2 {...} 

Catch: You must specify the Order for all of your members.

Be careful - deserialization will only work if the properties in the XML document are in the same order. Otherwise it will silently ignore out-of-order properties.

like image 151
Robert Harvey Avatar answered Sep 20 '22 01:09

Robert Harvey


XmlElementAttribute.Order, which controls "the explicit order in which the elements are serialized or deserialized".

like image 31
Tim Robinson Avatar answered Sep 19 '22 01:09

Tim Robinson