5

I am new in C# development,

In my project, I try to save a Dictionary instance by serializing it into a Settings storage with this code:

private static Dictionary<string, Dictionary<int, string>> GetKeys()
{
    Dictionary<string, Dictionary<int, string>> keys = null;
    try {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        keys = ser.Deserialize<Dictionary<string, Dictionary<int, string>>>(Settings.Default.keys);
    }
    catch (Exception e)
    {
        Debug.Print(e.Message);
    }
    return keys;
}

private static void SetKeys(Dictionary<string, Dictionary<int, string>> keys)
{
    try
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        Settings.Default.keys = ser.Serialize(keys);
    }
    catch (Exception e)
    {
        Debug.Print(e.Message);
    }
}

My problems occurs when I try to invoke SetKeys method. A ThreadAbortException is thrown:

A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll Evaluation requires a thread to run temporarily. Use the Watch window to perform the evaluation.

Have you got an idea how can I resolve my error?

Thanks

JNYRanger
  • 6,829
  • 12
  • 53
  • 81
alex
  • 5,661
  • 6
  • 33
  • 54
  • 3
    You may want to look at this http://stackoverflow.com/a/13754871/1099945 – gyosifov Jun 22 '15 at 13:54
  • 1
    Serializing/deserializing dictionaries is always a problem source. I'd suggest ditching the dictionary and create your own configuration collection extending https://msdn.microsoft.com/en-us/library/ms132438(v=vs.110).aspx as this is a keyed collection that is also a Collection, which is easily serialized/deserialized. –  Jun 22 '15 at 14:07

1 Answers1

3

Better use Json.NET, but if you want to use JavaScriptSerializer:

Try:

var json = new JavaScriptSerializer().Serialize(keys.ToDictionary(item => item.Key.ToString(), item => item.Value.ToString()));

Or:

string jsonString = serializer.Serialize((object)keys);
gyosifov
  • 3,193
  • 4
  • 25
  • 41