Last active
June 9, 2025 15:52
-
-
Save Kraballa/b7bd0578f15c4a45089152b5d53487ce to your computer and use it in GitHub Desktop.
Serializer class for serializing and deserializing any dictionary to xml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Xml.Serialization; | |
namespace Program | |
{ | |
public static class DictSerializer<K, V> where K : notnull | |
{ | |
public static void Serialize<T>(T data, string filename) where T : IDictionary<K, V> | |
{ | |
Tuple<K, V> pair = new(); | |
pair.Keys = data.Keys.ToArray(); | |
pair.Values = data.Values.ToArray(); | |
using (TextWriter writer = new StreamWriter(filename)) | |
{ | |
XmlSerializer serializer = new(typeof(Tuple<K, V>)); | |
serializer.Serialize(writer, pair); | |
} | |
} | |
public static Dictionary<K, V> Deserialize(string filename) | |
{ | |
object? obj; | |
using (TextReader reader = new StreamReader(filename)) | |
{ | |
XmlSerializer serializer = new(typeof(Tuple<K, V>)); | |
obj = serializer.Deserialize(reader); | |
} | |
if (obj == null) | |
throw new Exception("error, couldn't deserialize file"); | |
Tuple<K, V> tuple = (Tuple<K, V>)obj; | |
Dictionary<K, V> dict = new(); | |
for (int i = 0; i < tuple.Keys.Length; i++) | |
{ | |
dict.Add(tuple.Keys[i], tuple.Values[i]); | |
} | |
return dict; | |
} | |
} | |
[Serializable] | |
public class Tuple<K, V> | |
{ | |
[XmlArrayItem(ElementName = "Key")] | |
public K[] Keys; | |
[XmlArrayItem(ElementName = "Value")] | |
public V[] Values; | |
public Tuple() | |
{ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage: