C# - 反序列化 List<String>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2201851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:21:28  来源:igfitidea点击:

C# - Deserialize a List<String>

c#serializationextension-methods

提问by Vaccano

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. 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:

编辑:原来没有内置的 SerialzeObject。我之前在我的项目中做过一个,后来忘记了。当我找到它时,我以为它是内置的。如果你好奇,这是我制作的 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();
}

采纳答案by JaredPar

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

回答by CaffGeek

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,它就在那里,因为创建序列化器很慢,如果你一遍又一遍地使用相同的,这会加速你的应用程序。

回答by Jamie Keeling

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. In fact just looking at this now is going to make me rewrite this in a "using" block too.

这允许我将所有数据反序列化回 List<> 但我建议将其放在 try - catch 块中以确保安全。事实上,现在只看这个也会让我在“使用”块中重写它。

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.

抱歉,只是注意到您正在尝试以不同的方式进行操作,但无论如何我都会将答案留在那里。

回答by Brijesh Kumar Tripathi

I was getting error while deserializing to object. The error was "There is an error in XML document (0, 0)". I have modified the Deserialize function originally written by @JaredPar to resolve this error. It may be useful to someone:

反序列化为对象时出错。错误是“XML 文档 (0, 0) 中存在错误”。我修改了最初由@JaredPar 编写的 Deserialize 函数来解决这个错误。它可能对某人有用:

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