如何在序列化过程中为我的 ExpandoObject 命名?

How do I give a name to my ExpandoObject while serialize process?

我正在通过套接字向网络客户端发送数据,并且我将所有数据作为 json 字符串发送。为了尽量减少我发送到 webclient 的数据,我使用 ExpandoObject,所以我不向我的模型添加任何空变量,因此我不使用静态模型。到目前为止我一直在使用这个

List<ExpandoObject> categoryList= new List<ExpandoObject>();
for (int i = 0; i < mainForm.categories.Count; i++)
{
    ExpandoObject z = new ExpandoObject();
    (z as IDictionary<string, object>)["name"] = mainForm.categories[i].CategoryName;
    (z as IDictionary<string, object>)["prop1"] = HexConverter(mainForm.categories[i].prop1);
    (z as IDictionary<string, object>)["prop2"] = HexConverter(mainForm.categories[i].prop2);
    (z as IDictionary<string, object>)["prop3"] = HexConverter(mainForm.categories[i].prop3);
    (z as IDictionary<string, object>)["prop4"] = HexConverter(mainForm.categories[i].prop4);
    categoryList.Add(z);
}

现在这个工作正常我可以用

序列化它
var sssssss = JsonConvert.SerializeObject(new
                    {
                        xxx= yyy,
                        aaa= bbb,
                        qqq= www,
                        categoryList = categoryList
                    });

当我这样做时,我得到

正如你在图片中看到的,所有列表成员都已经用索引进行了序列化。所以我的问题是我能以某种方式为此设置一个值吗?而不是写 0,1,2 等? 我想使用名称 属性 而不是数字

您可以尝试使用 Dictionary<string, ExpandoObject> 而不是 List<ExpandoObject>:

var categoryList = new Dictionary<string, ExpandoObject>>();
for (int i = 0; i < mainForm.categories.Count; i++)
{
    ExpandoObject z = new ExpandoObject();
    (z as IDictionary<string, object>)["name"] = mainForm.categories[i].CategoryName;
    (z as IDictionary<string, object>)["prop1"] = HexConverter(mainForm.categories[i].prop1);
    (z as IDictionary<string, object>)["prop2"] = HexConverter(mainForm.categories[i].prop2);
    (z as IDictionary<string, object>)["prop3"] = HexConverter(mainForm.categories[i].prop3);
    (z as IDictionary<string, object>)["prop4"] = HexConverter(mainForm.categories[i].prop4);
    categoryList["someName" + i] = z;
}

我还要说的是,对于 z,您可以使用 Dictionary<string, object> 而不是 ExpandoObject