CrashCodes
CrashCodes

Reputation: 3287

In C#, How can I serialize Queue<>? (.Net 2.0)

At the XmlSerializer constructor line the below causes an InvalidOperationException which also complains about not having a default accesor implemented for the generic type.

Queue<MyData> myDataQueue = new Queue<MyData>();

// Populate the queue here


XmlSerializer mySerializer =
  new XmlSerializer(myDataQueue.GetType());    

StreamWriter myWriter = new StreamWriter("myData.xml");
mySerializer.Serialize(myWriter, myDataQueue);
myWriter.Close();

Upvotes: 9

Views: 14744

Answers (4)

Gianmaria Dalla Torre
Gianmaria Dalla Torre

Reputation: 91

In my case i had a dynamic queue and i had to save and load the state of this one.

Using Newtonsoft.Json:

List<dynamic> sampleListOfRecords = new List<dynamic>();
Queue<dynamic> recordQueue = new Queue<dynamic>();
//I add data to queue from a sample list
foreach(dynamic r in sampleListOfRecords)
{
     recordQueue.Enqueue(r);
}

//Serialize
File.WriteAllText("queue.json",
     JsonConvert.SerializeObject(recordQueue.ToList(), Formatting.Indented));
//Deserialize
List<dynamic> data = 
     JsonConvert.DeserializeObject<List<dynamic>>(File.ReadAllText("queue.json"));

Upvotes: 0

user1228
user1228

Reputation:

Not all parts of the framework are designed for XML serialization. You'll find that dictionaries also are lacking in the serialization department.

A queue is pretty trivial to implement. You can easily create your own that also implements IList so that it will be serializable.

Upvotes: 1

Asher
Asher

Reputation: 1867

if you want to use the built in serialization you need to play by its rules, which means default ctor, and public get/set properties for the members you want to serialize (and presumably deserialize ) on the data type you want to serialize (MyData)

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063005

It would be easier (and more appropriate IMO) to serialize the data from the queue - perhaps in a flat array or List<T>. Since Queue<T> implements IEnumerable<T>, you should be able to use:

List<T> list = new List<T>(queue);

Upvotes: 16

Related Questions