Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 443
Sinan Barut Avatar asked Mar 10 '26 22:03

Sinan Barut


1 Answers

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

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

like image 144
Ivan Sanz Carasa Avatar answered Mar 13 '26 12:03

Ivan Sanz Carasa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!