Reputation: 1479
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.
Upvotes: 8
Views: 11624
Reputation:
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.
Upvotes: 20