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

十年热恋 提交于 2019-12-23 07:58:35

问题


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();

回答1:


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);



回答2:


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.




回答3:


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)




回答4:


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"));


来源:https://stackoverflow.com/questions/310167/in-c-how-can-i-serialize-queue-net-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!