alex
alex

Reputation: 5721

C# - JSON Serialization of Dictionary

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

Upvotes: 5

Views: 2822

Answers (1)

gyosifov
gyosifov

Reputation: 3223

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);

Upvotes: 3

Related Questions