-2

Very simple question. Hope its easy...

Dictionary<int, string> dict = PLCCommunicator.getVarForSchakelingen("iOffsetSun", plc);
return Json(new { succeeded = true, dict }, JsonRequestBehavior.AllowGet);

Is there a way in which the dict can easily be converted? Something like dict.ToJson()

My controller returns a JsonResult...

Kip ei
  • 479
  • 6
  • 20
  • This question isn't really well researched. Google is your friend. This question is similar to [this post](http://stackoverflow.com/questions/4861138/c-sharp-json-serialization-of-dictionary-into-keyvalue-instead-of-keyk). And [this post](http://stackoverflow.com/questions/32006310/serialize-and-deserialize-dictionaryint-object-using-javascriptserializer-and) and [this post](http://stackoverflow.com/questions/10197059/serialize-dictionaryint-object-using-json-net). You get the idea. – franklin Mar 02 '16 at 15:32
  • I found a few myself(not all, so thanks for that!), still it involves coding ánd testing that code. I was hoping for a library to do it for me... – Kip ei Mar 02 '16 at 15:36

1 Answers1

0

You can create a extension method using JsonConvert class:

public static class DictionaryExtensions
{
    public static string ToJson<TKey, TValue>(this Dictionary<TKey, TValue> dictionary)
    {
        return JsonConvert.SerializeObject(dictionary);
    }
}

Then you can do:

Dictionary<int, string> dict = PLCCommunicator.getVarForSchakelingen("iOffsetSun", plc);
return Json(new { succeeded = true, jsonDict = dict.ToJson() }, JsonRequestBehavior.AllowGet);
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
  • Thank you, I also found `JsonConvert.SerializeObject(dict);` I am also thinking about making a wrapper class instead of using a Dictionary, since it is easier at the client side to parse a wrapper serialized to json instead of a dict serialized to json. I am not so experienced at this...Any suggestion/opinion about this is welcome... – Kip ei Mar 02 '16 at 16:05
  • @Kipei: You can works with dictionary in server side and use wrapper in client side since the json is the same, however in your case you are using numbers as key, so wrapper is not an option. What options is better if use a class of dictionary, depends how dynamic is your data. if you have well defined information to send then use a model. if you can't know what information will be sent until runtime then uses a dictionary – Arturo Menchaca Mar 02 '16 at 16:26