0

I have a Dictionary and i want to serialize it to call a method. In this method i wiil recive a string and i need to deserialize it to use. I want the way to convert Dictionary to string and to convert string to Dictionary again. There is any way to do it without using files?

Finally the code i've used is:

private string Serialize(Dictionary<string, object> parameters)
{
    using (MemoryStream memoryStream = new MemoryStream()) {
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(memoryStream, parameters);
        return Convert.ToBase64String(memoryStream.ToArray());
    }
}

private Dictionary<string, object> Deserialize(string data)
{
    using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(data))) {
        IFormatter formatter = new BinaryFormatter();
        memoryStream.Seek(0, SeekOrigin.Begin);
        return (Dictionary<string, object>)formatter.Deserialize(memoryStream);
    }
}

Thanks!

  • Hi, and welcome to SO! There is not a lot of info in your question. For instance, do you need to send the data over a network or something, since you want to serialize it? Also, do you have control over the method where data will be deserialized? (Otherwise, you'll need to be sure to serialize it in the correct format, to ensure correct recreation of your object). Short answer: Serialize your object to binary, then convert to a Base64 string. On the other end, reverse the operation. See my answer below for an example. – Kjartan Jul 24 '14 at 13:22
  • Alvaro -- please put the final code you used into the original question (as an update), instead of the answer. – Michael Paulukonis Jul 24 '14 at 14:20

3 Answers3

1

Sounds like you want something like the following. Note that I haven't tested this, so no guarantees, but I believe this should work:

var yourDictionary = ...;     

MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();

// Store your object in memoryStream...
binaryFormatter.Serialize(memoryStream, yourDictionary);

// ... and convert that to a string:
string dictionaryAsText = Convert.ToBase64String(memoryStream.ToArray());

Now you can pass dictionaryAsText to your method, and recreate the object as follows:

var memoryStream = Convert.FromBase64String(dictionaryAsText)

IFormatter formatter = new BinaryFormatter();
memoryStream.Seek(0, SeekOrigin.Begin);
Dictionary<string, object> intermediateObject = 
            (Dictionary<string, object>) formatter.Deserialize(stream);
Kjartan
  • 18,591
  • 15
  • 71
  • 96
0

You would like to serialize a dictionnary ?

This post provides you some solutions : How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

Do do it directly in a string, assume you have a dictionnary : Dictionary

        Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();
        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
        StringWriter textWriter = new StringWriter();
        string output ="<Dictionary>";
        foreach (TKey key in dict.Keys)
        {
            output += "<item>";
            output += "<key>";

            keySerializer.Serialize(textWriter, key);
            output += textWriter.ToString();
            output += "</key>";


            output += "<value>";
            TValue value = this[key];
            keySerializer.Serialize(textWriter, key);
            output += textWriter.ToString();
            output += "</value>";

            output += "</item>";
        }
        output += "</Dictionary>";

You can the deserialize your Dictionary by parsing your xml string with the following function :

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(output);
Community
  • 1
  • 1
Fabien
  • 194
  • 1
  • 10
  • use flay if the question was already asked and having a solution within stack overflow. – Suji Jul 24 '14 at 12:38
0

If you only want to convert a dictionary to a string and vice versa you can just write two small conversion functions.

An example:

private string Dict2String(Dictionary<int, string> dict)
{
    string str = string.Empty;

    foreach (KeyValuePair<int, string> entry in dict)
    {
        if (str.Length > 0)
            str += ";";

        str += entry.Key.ToString() + ";" + entry.Value.ToString();
    }

    return str;
}

private Dictionary<int, string> String2Dict(string str)
{
    string[] parts = str.Split(';');
    Dictionary<int, string> dict = new Dictionary<int, string>(parts.Length / 2);

    for (int i = 0; i < parts.Length / 2; ++i)
        dict.Add(int.Parse(parts[i * 2]), parts[i * 2 + 1]);

    return dict;
}

This example uses a dictionary with an integer key and a string value. But you can adjust the code for your needs.

Robert S.
  • 1,942
  • 16
  • 22
  • 1
    Your solution doesn't work if there is separators ';' in your dictionary. – antoinestv Jul 24 '14 at 13:17
  • Yes it's just an example. Feel free to use a separator that is surely not inside your dictionary. It's possible to use string-separators as well like "KeyValue". – Robert S. Jul 24 '14 at 22:19