连载字典< INT,对象>使用JSON.net? [英] Serialize Dictionary<int,object> using JSON.net?

查看:117
本文介绍了连载字典< INT,对象>使用JSON.net?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用JSON.net序列化词典。

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

使用

JsonConvert.SerializeObject(theDict);

下面是我的结果。

{
  "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
  },
  ...
  ...
  ...
}  

有没有办法来序列本字典,这样的按键呈现为有效的JavaScript变量?

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.

推荐答案

这是生成的JSON 词典<的正确方法; INT,...> 。其原因是, JSON的需要的所有按键都带引号的字符串

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在这方面更放松一点:但是JSON是JS对象文字的受限制的。在任何情况下,的 JavaScript中的所有属性名称都是字符串的。 (它们被隐式转换为需要的。)因此,({1:2})[1])({1: 2})[1])是如JS同样有效(两者计算结果为 2 ),但只有 { 1:2} 是有效的JSON

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.

如果目标类型反序列化回为词典< INT。 ...方式> 然后它会自动照顾的键转​​换到 INT ,IIRC

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.

我不知道的一种方式来获得JSON.NET产生非直接JSON它;-)可以与循环顶层结构,比如做每个 KeyValuePair< INT,...> 并生成JSON用于与改良的JS代码沿着每个条目:

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)));
}



其中,的Emit 是无论是用于收集输出......我会建议只是正常的JSON如果可能的话,虽然。

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

编码愉快。

这篇关于连载字典&LT; INT,对象&gt;使用JSON.net?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆