我有这个员工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中添加额外的“部门”财产。
请帮助。
答案 0 :(得分:4)
您可以从员工创建中间anonymous type并序列化:
var extendedEmployees = employees.Select(employee => new
{
employee.Id,
employee.Name,
Department = "Computer Science",
}
var json = JsonConvert.Serialize(extendedEmployees)