2

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.

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.