KowalskyJan
KowalskyJan

Reputation: 1

Object serialization how to

how to fast (not many to do) serialize that object ?

Dictionary<int, List<int[,]>>

orginal XmlSerializer not support Dictionary and array[,]

Upvotes: 0

Views: 132

Answers (2)

AllenG
AllenG

Reputation: 8190

If you specifically need XML Serialization, a custom class might help you. Since you're not actually doing a KeyValuePair try something like this:

[XMLSerializable]
public class CustomDictionary
{
    public int Key {get; set;}
    public List<Coordinate> Value {get; set;}
}

[XMLSerializable]
public class Coordinate
{
   public int X;
   public int Y;
}

That assumes that the standard Point (which I believe is a Double X, Double Y) won't work, and that you're only holding one value in each column of your int array. You could modify that container class to fit your specific needs, of course.

Once you've marked up your code correctly (no- I don't think this is) you would just be able to call the stock XmlSerializer to write to XML.

Upvotes: 0

mellamokb
mellamokb

Reputation: 56779

Edit:

Since Dictionary is not supported by XmlSerializer my original answer is incorrect, but I provide for reference of other serialization. A better answer is to implement your own KeyValuePair class and transform the Dictionary to this class so it can be serialized. A good explanation of how to implement and why this is necessary can be found here.


NOTE: This is my old answer and incorrect.

This example uses the built-in .Net XmlSerializer class to serialize into a string. The serializer can write to any stream, so for example if you are serializing to file, you would want to use a FileWriter instead of a StringWriter.

// serialize into a string
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);

// create a serializer for my specific type
XmlSerializer ser = new XmlSerializer(typeof(Dictionary<int, List<int[,]>>));

// perform serialization
ser.Serialize(sw, myObj);

// retrieve the final serialized result as a string I can work with
string serialized = sb.ToString();

// do something with serialized object

Upvotes: 1

Related Questions