使用带有嵌套字典的json.net序列化对象

时间:2015-09-11 17:37:46

标签: c# json

我在序列化JSON对象时有点迷失,我正在尝试将Item类序列化为JSON

class Item
{
    public Dictionary<string, object> components = new Dictionary<string, object> { };
    public string mixins { get; set; }
    public string type { get; set; }
}

class Components
{
    public Dictionary<string, object> unit_info = new Dictionary<string, object> { };
    public Dictionary<object, object> generateUnitInfo()
    {
        unit_info.Add("bla", "blubb");
        unit_info.Add("blubb", "bla");
        return unit_info;
    }
}

我的JSON应该看起来像这样

{
   "components": {
      "unit_info" : {
         "bla": "blubb",
         "blubb": "bla",
      },
   }
}

任何提示都会有所帮助,在此先感谢

编辑:那是我到目前为止的代码

Component c = new Component();
Item item = new Item();
item.type = CBItemType.SelectedItem.ToString();
item.mixins = "test mixins";

item.components.Add(c.unit_info, c.generateUnitInfo());
string json = JsonConvert.SerializeObject(item, Formatting.Indented);

这就是我得到的

{
  "mixins": "test mixins",
  "type": "entity",
  "components": {
    "(Collection)": {
      "bla": "blubb",
      "blubb": "bla"
    }
  },
  "entity_data": {}
}

generateUnitInfo方法向unit_info添加2 k / v对,我想要而不是(Collection)unit_info

1 个答案:

答案 0 :(得分:1)

您可以使用匿名对象(Json.Net

var obj = new { components = new { unit_info = new { bla="blubb", blubb="bla" } } };
var json = JsonConvert.SerializeObject(obj);

内置 JavaScriptSerializer 也会产生相同的结果

var json = new JavaScriptSerializer().Serialize(obj);

PS:如果使用字典是必须的,你也可以使用它

var obj = new Dictionary<string, object>()
{
    {
        "components", new Dictionary<string,object>()
        {
            {
                "unit_info" , new Dictionary<string,object>()
                {
                    { "bla", "blubb" }, {"blubb", "bla" }
                }
            }
        }
    }
};

两个序列化程序都将返回您期望的json。