简体   繁体   中英

Serialize Dictionary<int,object> using JSON.net?

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.

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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM