将 属性 添加到 json 数组的所有对象

Add property to all objects of json array

我有这个员工 DTO

Class Employee
{
   int Id {get; set;}
   string Name {get; set;}
}

在我的代码中,我获取了 Employee 对象的集合并将其序列化,如下所示

string JsonString = JsonConvert.SerializeObject(employees); // where employees is IEnumerable<Employee>

我得到的 JsonString 是

[{"Id":1,"Name":"John"},
{"Id":2,"Name":"Mark"},
{"Id":3,"Name":"Pete"}]

现在我想再添加一个 属性 到 json 数组中存在的所有这些对象

[{"Id":1,"Name":"John","Department":"Computer Science"},
{"Id":2,"Name":"Mark","Department":"Computer Science"},
{"Id":3,"Name":"Pete","Department":"Computer Science"}]

挑战在于我不想向我现有的 Employee Dto 添加额外的 属性 "Department"。

请帮忙。

您可以从您的员工创建一个中间体 anonymous type 并将其序列化:

var extendedEmployees = employees.Select(employee => new
                        {
                            employee.Id,
                            employee.Name, 
                            Department = "Computer Science",
                        }

var json = JsonConvert.Serialize(extendedEmployees)