Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


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:

// 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();
}
like image 686
Vaccano Avatar asked Feb 04 '10 17:02

Vaccano


2 Answers

There is no such builtin method as SerializeObject but it's not terribly difficult to code one up.

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);
  }
}
like image 155
JaredPar Avatar answered Oct 11 '22 20:10

JaredPar


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.

like image 30
CaffGeek Avatar answered Oct 11 '22 21:10

CaffGeek