Thordax
Thordax

Reputation: 1733

serializable dictionary in .NET in Framework 2.0

I search for a serializable dictionary in c# (framework 2.0), and I found this one :

http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx

which is pretty nice but I would like to have it serialize my dictionary like this :

<item>
    <key>my_first_key</key>
    <value>my_first_value</value>
</item>
<item>
    <key>my_second_key</key>
    <value>my_second_value</value>
</item>

I tried to modify the writeXml method like this :

writer.WriteStartElement("item")
writer.WriteElementString("key", key.ToString)   
writer.WriteElementString("value", value.ToString)  

And it works fine, but to deserialize the xml input as a dictionary, i don't manage to make it work. I tried this :

reader.ReadStartElement("item")

reader.ReadStartElement("key")
Dim key As String = reader.ReadString()

And i get the key correctly, but into a String object. And when i try to add my key/value pair like this :

Me.Add(key, value)

It doesn't work since key is a string and not a TKey type. Do you know how to "cast" or convert a string into a TKey ? Or encapsulate the key/value as a string into a TKey/Tvalue type ?

Thanks a lot in advance!

Upvotes: 1

Views: 519

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063994

Your requirement seems to focus very much on string, while the code as proposed is generic. However, you can probably special case this, i.e.

reader.ReadStartElement("key");
if(typeof(TKey) == typeof(string)) {
    TKey key = (TKey)(object)reader.ReadString();
} else {           
    TKey key = (TKey)keySerializer.Deserialize(reader);
}
reader.ReadEndElement();

(and likewise for the value)

and:

writer.WriteStartElement("item")
if(typeof(TKey) == typeof(string)) {
    writer.WriteElementString("key", (string)(object)key);
} else {
    writer.WriteStartElement("key");
    keySerializer.Serialize(writer, key);
    writer.WriteEndElement();
}

(and similar for the value)

Untested - but should do the job.

Upvotes: 1

Related Questions