如何正确(de)序列化c#中的嵌套对象?

时间:2017-08-14 16:10:22

标签: c# xmlserializer

编辑:抱歉,代码按预期工作。我只是未能正确测试。很抱歉给您带来不便

我在SO上找到了一些代码来存储和加载对象(代码到底)。存储文件正常工作,但是当你有一个对象列表时,将文件重新送回对象是不起作用的:

执行

Block b = loadFile<Block>("file");
Console.WriteLine(b.allCoins.Count); //is 0

导致列表为空。检查xml文件它们都被正确存储,这意味着加载在某种程度上不起作用。 如何正确加载对象?

这是块类:

[Serializable]
    public class Block {
        public struct Coin {
            public string owner;
            public string name;

            public Coin(string n, string o) {
                owner = o;
                name = n;
            }
        };

        public int name;
        public List<string> hashOfParticles;
        public int numberOfTransactions;
        public List<Coin> allCoins;
     }
 }

以下是我如何将文件加载到对象中:

public static T loadFile<T>(string fileName) {
            if (string.IsNullOrEmpty(fileName)) { return default(T); }

            T objectOut = default(T);

            try {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(fileName);
                string xmlString = xmlDocument.OuterXml;

                using (StringReader read = new StringReader(xmlString)) {
                    Type outType = typeof(T);

                    XmlSerializer serializer = new XmlSerializer(outType);
                    using (XmlReader reader = new XmlTextReader(read)) {
                        objectOut = (T)serializer.Deserialize(reader);
                        reader.Close();
                    }

                    read.Close();
                }
            } catch (Exception ex) {
                //Log exception here
            }

            return objectOut;
        }

以下是存储文件的代码:

public static void storeFile<T>(T serializableObject, string fileName) {
            if (serializableObject == null) { return; }

            try {
                XmlDocument xmlDocument = new XmlDocument();
                XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
                using (MemoryStream stream = new MemoryStream()) {
                    serializer.Serialize(stream, serializableObject);
                    stream.Position = 0;
                    xmlDocument.Load(stream);
                    xmlDocument.Save(fileName);
                    stream.Close();
                    Form1.instance.addToLog("Storing \"" + fileName +  "\" succesful");
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
                Form1.instance.addToLog("Storing \"" + fileName + "\" NOT succesful");

            }
        }

0 个答案:

没有答案