Sinan Barut
Sinan Barut

Reputation: 540

How to set null for looping value when serialize

I could not find a title for my question. I have class as below

class Employee
{
    public string Name { get; set; }
    public List<Employee> Subordinates { get; set; }
} 

if i serialize this class object, it is look like as below

[
  {
    "Name": "first person",
    "Subordinates": [
      {
        "Name": "second person",
        "Subordinates": null
      }
    ]
  },
  {
    "Name": "second person",
    "Subordinates": null
  }
]

But i need it like this

[
  {
    "Name": "first person",
    "Subordinates": null
  },
  {
    "Name": "second person",
    "Subordinates": null
  }
]

How can i get this I am not using only this class. I have many class like employee so i need one solution for my all classes. I am using below code for one class. I know it's not a solution, but i didn't find any better solution

var employees = //sql query .ToList()
foreach(var item in employees){
    item.Subordinates = null;
}

return Json(employess)

Upvotes: 3

Views: 91

Answers (1)

Ivan Sanz Carasa
Ivan Sanz Carasa

Reputation: 1387

Depending on what serializer you are using, the solution differs.

Try adding [NonSerialized] [XmlIgnore] [ScriptIgnore] to the List property.

Upvotes: 1

Related Questions