8

I'm trying to use JSON.net to serialize a Dictionary.

Using

JsonConvert.SerializeObject(theDict); 

Here is my result

{ "1": { "Blah1": false, "Blah2": false, "Blah3": "None", "Blah4": false }, "2": { "Blah1": false, "Blah2": false, "Blah3": "None", "Blah4": false }, "3": { "Blah1": false, "Blah2": false, "Blah3": "None", "Blah4": false }, ... ... ... } 

Is there a way to serialize this dictionary such that the keys are rendered as valid javascript variables?

I am also open to other strategies of serializing the dictionary.

6
  • 3
    They are valid. What would you like the output to look like? Commented Apr 17, 2012 at 18:41
  • 2
    Technically, your variable["1"] is valid. Commented Apr 17, 2012 at 18:41
  • 1
    What is going to be the consumer of the produced JSON? If it is going to be javascript then just use JSON.parse deserialize the JSON back to a JS object. Commented Apr 17, 2012 at 18:51
  • 1
    Ahhh I see. Are those indexs rather than variables? So object[1] vs object.1? Am I interpreting that correctly? Commented Apr 17, 2012 at 19:18
  • 2
    object["1"] not object[1]. Commented Apr 17, 2012 at 19:40

1 Answer 1

20

That is the correct way to generate the JSON for Dictionary<int,...>. The reason is that JSON requires that all keys are quoted-string literals.

JS is a little more relaxed in this regard: but JSON is a restricted form of JS object literals. In any case, all property names in JavaScript are strings. (They are implicitly converted as needed.) Thus, ({1: 2})["1"]) and ({"1": 2})[1]) are as equally valid in JS (and both evaluate to 2), but only {"1": 2} is valid JSON.

If the target Type to deserialize back into is Dictionary<int,...> then it will automatically take care of the conversions in the keys to int, IIRC.

I am not aware of a way to get JSON.NET to generate non-JSON directly ;-) It could be done with looping the top-level construct, e.g. each KeyValuePair<int,...> and generating the JSON for each individual entry along with the "modified" JS code:

foreach (var p in dict) { var k = p.Key; var v = p.Value; Emit(string.Format( "var name{0} = {1};", k, JsonConvert.SerializeObject(v))); } 

Where Emit is whatever is used to collect the output... I would recommend "just normal JSON" if at all possible, though.

Happy coding.

Sign up to request clarification or add additional context in comments.

1 Comment

I was able to puzzle out as much from the comments above and a little research, but it's always nice to get a very specific explanation. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.