What is the best way to serialize / deserialize a <String, String> dictionary in .Net 2.0?

I need to be able to serialize / deserialize the dictionary for a human-readable (and if comes to it, human-editable) string (preferably XML or Json).

I only need to work with string dictionaries, and not with any other types of objects. Strings, however, are considered free text, so they can have characters such as single / double quotes, etc. Therefore they must be encoded / escaped correctly.

This project is based on .Net 2.0, so I cannot use JSON.Net, unfortunately.

Any ideas how best to do this fast?

I could obviously write my own code to do this, but I expect to remove a lot of headaches if I go this way, especially the deserializing part.

Any ideas would be appreciated. Thank!
Daniel

+2
dictionary serialization
Jul 10 '09 at 20:14
source share
3 answers

As far as I know, there are currently three easy to implement solutions:

1) JSON.Net, which works in .Net 2.0 with a separate binary (makes things REALLY easy, and json makes it a good format, more compact than xml).

2) Implementation of the Serializable Dictionary, for example: http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx (Note that this version does not handle binary serialization (BinaryFormatter) due to missing constructors and the missing attribute "[Serializable]", but it takes 2 minutes to fix it - I want the author to update the message!)

3) SharpSerializer also makes things simple, although the Xml output is rather cumbersome by default (I haven’t tried playing with the settings).

Sorry to post this so late, but I'm not sure why the question languishes as unanswered, and I think that any of these answers will help the random seeker!

UPDATE: Apparently, I missed one, NXmlSerializer , although I did not play with it - I have no idea how it compares with others.

+2
Jun 20 '10 at 19:13
source share

I think the easiest way is to create a wrapper class that is easily serializable in the XML serializer and hidden in the Dictionary<string,string> and vice versa. This will make editing easier and eliminate all screening issues.

for example

 public class Wrapper { public List<string> Keys {get; set; } public List<string> Values {get; set; } public Wrapper() {} public Wrapper(Dictionary<string,string> map) { Keys = new List<string>(map.Keys); Values = new List<string>(map.Values); } public Dictionary<string,string> GetMap() { Dictionary<string,string> map = new Dictionary<string,string>(); for ( int i = 0; i < Keys.Length; i++ ) { map[Keys[i]] = Values[i]; } return map; } } 
+1
Jul 10 '09 at 20:27
source share

Add IXmlSerializable , it will be very simple.

Pseudocode:

 public class CoolHash : Dictionary<String, String>, IXmlSerializable { void WriteXml(XmlWriter writer){ foreach(string key in this.Keys){ writer.WriteElementText(key, this[key]); } } } 
0
Jul 10 '09 at 20:21
source share



All Articles