Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - JSON Serialization of Dictionary

Tags:

c#

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

like image 820
alex Avatar asked Oct 19 '22 08:10

alex


1 Answers

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);
like image 109
gyosifov Avatar answered Nov 15 '22 04:11

gyosifov