简体   繁体   English

序列化字典 <int,object> 使用JSON.net?

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

I'm trying to use JSON.net to serialize a Dictionary. 我正在尝试使用JSON.net来序列化字典。

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? 有没有办法序列化这个字典,以便将键呈现为有效的javascript变量?

I am also open to other strategies of serializing the dictionary. 我也对序列化字典的其他策略持开放态度。

That is the correct way to generate the JSON for Dictionary<int,...> . 这是为Dictionary<int,...>生成JSON的正确方法。 The reason is that JSON requires that all keys are quoted-string literals . 原因是JSON 要求所有键都是带引号的字符串文字

JS is a little more relaxed in this regard: but JSON is a restricted form of JS object literals. JS在这方面稍微宽松一些:但JSON是JS对象文字的限制形式。 In any case, all property names in JavaScript are strings . 在任何情况下, JavaScript中的所有属性名称都是字符串 (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. (它们会根据需要进行隐式转换。)因此, ({1: 2})["1"])({"1": 2})[1])在JS中同样有效(并且都评估为2 ),但只有{"1": 2}是有效的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. 如果要反序列化的目标类型是Dictionary<int,...>那么它将自动处理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: 我不知道让JSON.NET直接生成非JSON的方法;-)可以通过循环顶层构造来完成,例如每个KeyValuePair<int,...>并为每个人生成JSON条目以及“修改过的”JS代码:

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. Emit是用于收集输出的任何东西......但是如果可能的话,我会建议“只是普通的JSON”。

Happy coding. 快乐的编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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