本文介绍了使用带有嵌套字典的json.net序列化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm a little lost with serializing a JSON object, I'm trying to serialize the Item class into a 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应该看起来像这样

My JSON should look like this

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

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

Any hint would be helpful, thanks in advance

多数民众赞成在到目前为止我拥有的代码

thats the code that I have so far

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

The generateUnitInfo method adds 2 k/v pairs to the unit_info, I want instead of (Collection) unit_info

推荐答案

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

You can use anonymous objects (Json.Net)

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

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

Built-in JavaScriptSerializer would give the same result too

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

PS:如果必须使用字典,那么您也可以使用它

PS: If using dictionary is a must you can use it too

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

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

Both serializers will return your expected json.

这篇关于使用带有嵌套字典的json.net序列化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:25