C # - JSON Dictionary Serialization

I'm new to C # development,

In my project, I am trying to save a Dictionary instance by serializing it into the Settings repository using 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 arise when I try to call the SetKeys method. A ThreadAbortException :

The first random error like "System.Threading.ThreadAbortException" occurred in mscorlib.dll. Evaluation requires that the thread run temporarily. Use the Watch window to evaluate.

Do you have an idea how I can resolve my mistake?

thanks

+5
source share
1 answer

Better to 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); 
+3
source

All Articles