>我有这个员工 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"}]
挑战在于我不想向现有的员工 Dto 添加额外的属性"部门"。
请帮忙。
您可以从员工创建中间匿名类型并序列化该类型:
var extendedEmployees = employees.Select(employee => new
{
employee.Id,
employee.Name,
Department = "Computer Science",
}
var json = JsonConvert.Serialize(extendedEmployees)