Gk_999
Gk_999

Reputation: 518

Add property to all objects of json array

I have this Employee DTO

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

In my code I'm getting collection of Employee objects & serializing it as shown below

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

The JsonString that i get here is

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

Now I want to add one more property to all these objects present in the json array

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

The challenge is that i don't want to add extra property "Department" to my existing Employee Dto.

Please Help.

Upvotes: 2

Views: 1674

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149548

You can create an intermediate anonymous type from your employees and serialize that:

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

var json = JsonConvert.Serialize(extendedEmployees)

Upvotes: 4

Related Questions