Search code examples
c#json.netexpandoobject

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


I'm sending data to a webclient via sockets and I send all of my data as json string. In order to minimize the data I send to webclient I use ExpandoObject so I do not add any empty variable to my model therefore I don't use static model. So far I was using this

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

now this works fine I can serialize it with

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

When I do so I get

this

as you can see in the picture all list members has been serialized with indicies. So my question here is can I somehow set a value for this? Instead of writing 0,1,2 etc.? I want use the name property instead of the numbers


Solution

  • You can try using Dictionary<string, ExpandoObject> instead of 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;
    }
    

    Also I would say that you can use Dictionary<string, object> instead of ExpandoObject for z.