简体   繁体   English

C# - 反序列化列表<String>

[英]C# - Deserialize a List<String>

I can serialize a list really easy:我可以很容易地序列化一个列表:

List<String> fieldsToNotCopy =new List<String> {"Iteration Path","Iteration ID"};
fieldsToNotCopy.SerializeObject("FieldsToNotMove.xml");

Now I need a method like this:现在我需要这样的方法:

List<String> loadedList = new List<String();
loadedList.DeserializeObject("FieldsToNotMove.xml");

Is there such a method?有没有这样的方法? Or am I going to need to create an XML reader and load it in that way?还是我需要创建一个 XML 阅读器并以这种方式加载它?


EDIT: Turns out there is no built in SerialzeObject.编辑:原来没有内置的 SerialzeObject。 I had made one earlier in my project and forgot about it.我在我的项目中早些时候做了一个,然后忘记了。 When I found it I thought it was built in. In case you are curious this is the SerializeObject that I made:当我找到它时,我认为它是内置的。如果你好奇,这是我制作的 SerializeObject:

// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
   XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
   TextWriter textWriter = new StreamWriter(filename);

   xmlSerializer.Serialize(textWriter, toSerialize);
   textWriter.Close();
}

There is no such builtin method as SerializeObject but it's not terribly difficult to code one up. 没有像SerializeObject那样的内置方法,但编写一个方法并不是非常困难。

public void SerializeObject(this List<string> list, string fileName) {
  var serializer = new XmlSerializer(typeof(List<string>));
  using ( var stream = File.OpenWrite(fileName)) {
    serializer.Serialize(stream, list);
  }
}

And Deserialize 并反序列化

public void Deserialize(this List<string> list, string fileName) {
  var serializer = new XmlSerializer(typeof(List<string>));
  using ( var stream = File.OpenRead(fileName) ){
    var other = (List<string>)(serializer.Deserialize(stream));
    list.Clear();
    list.AddRange(other);
  }
}

These are my serialize/deserialize extension methods that work quite well 这些是我的序列化/反序列化扩展方法,可以很好地工作

public static class SerializationExtensions
{
    public static XElement Serialize(this object source)
    {
        try
        {
            var serializer = XmlSerializerFactory.GetSerializerFor(source.GetType());
            var xdoc = new XDocument();
            using (var writer = xdoc.CreateWriter())
            {
                serializer.Serialize(writer, source, new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") }));
            }

            return (xdoc.Document != null) ? xdoc.Document.Root : new XElement("Error", "Document Missing");
        }
        catch (Exception x)
        {
            return new XElement("Error", x.ToString());
        }
    }

    public static T Deserialize<T>(this XElement source) where T : class
    {
        try
        {
            var serializer = XmlSerializerFactory.GetSerializerFor(typeof(T));

            return (T)serializer.Deserialize(source.CreateReader());
        }
        catch //(Exception x)
        {
            return null;
        }
    }
}

public static class XmlSerializerFactory
{
    private static Dictionary<Type, XmlSerializer> serializers = new Dictionary<Type, XmlSerializer>();

    public static XmlSerializer GetSerializerFor(Type typeOfT)
    {
        if (!serializers.ContainsKey(typeOfT))
        {
            System.Diagnostics.Debug.WriteLine(string.Format("XmlSerializerFactory.GetSerializerFor(typeof({0}));", typeOfT));

            var newSerializer = new XmlSerializer(typeOfT);
            serializers.Add(typeOfT, newSerializer);
        }

        return serializers[typeOfT];
    }
}

You just need to define a type for your list and use it instead 您只需要为列表定义类型并使用它

public class StringList : List<String> { }

Oh, and you don't NEED the XmlSerializerFactory, it's just there since creating a serializer is slow, and if you use the same one over and over this speeds up your app. 哦,你不需要XmlSerializerFactory,它就在那里,因为创建一个序列化器很慢,如果你反复使用同一个,这会加速你的应用程序。

I'm not sure whether this will help you but I have dome something which I believe to be similar to you. 我不确定这是否会对你有所帮助,但我有一些我相信与你相似的东西。

//A list that holds my data
private List<Location> locationCollection = new List<Location>();


public bool Load()
{
            //For debug purposes
            Console.WriteLine("Loading Data");

            XmlSerializer serializer = new XmlSerializer(typeof(List<Location>));
            FileStream fs = new FileStream("CurrencyData.xml", FileMode.Open);

            locationCollection = (List<Location>)serializer.Deserialize(fs);

            fs.Close();

            Console.WriteLine("Data Loaded");
            return true;
}

This allows me to deserialise all my data back into a List<> but i'd advise putting it in a try - catch block for safety. 这允许我将我的所有数据反序列化为List <>但我建议将它放在try-catch块中以确保安全。 In fact just looking at this now is going to make me rewrite this in a "using" block too. 事实上,现在只是看着这个就会让我在“使用”块中重写它。

I hope this helps. 我希望这有帮助。

EDIT: 编辑:

Apologies, just noticed you're trying to do it a different way but i'll leave my answer there anyway. 道歉,只是注意到你试图以不同的方式做到这一点,但无论如何我会留下我的答案。

I was getting error while deserializing to object. 反序列化反对时遇到错误。 The error was "There is an error in XML document (0, 0)" . 错误是“XML文档(0,0)中存在错误” I have modified the Deserialize function originally written by @JaredPar to resolve this error. 我修改了最初由@JaredPar编写的反序列化函数来解决此错误。 It may be useful to someone: 它可能对某人有用:

public static void Deserialize(this List<string> list, string fileName)
{
    XmlRootAttribute xmlRoot = new XmlRootAttribute();
    xmlRoot.ElementName = "YourRootElementName";
    xmlRoot.IsNullable = true;

    var serializer = new XmlSerializer(typeof(List<string>), xmlRoot);
    using (var stream = File.OpenRead(fileName))
    {
        var other = (List<string>)(serializer.Deserialize(stream));
        list.Clear();
        list.AddRange(other);
    }
}

Create a list of products be serialized创建要序列化的产品列表

List<string> Products = new List<string>
{
  new string("Product 1"),
  new string("Product 2"),
  new string("Product 3"),
  new string("Product 4")
};

Serialization序列化

using (FileStream fs = new FileStream(@"C:\products.txt", FileMode.Create))
{
   BinaryFormatter bf = new BinaryFormatter();
   bf.Serialize(fs, Products);
}

Deserialization反序列化

using (FileStream fs = new FileStream(@"C:\products.txt", FileMode.Open))
{
    BinaryFormatter bf = new BinaryFormatter();
    var productList = (List<string>)bf.Deserialize(fs);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM