I have the following code in a controller.
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
}
public ActionResult JsonObject()
{
Person[] persons = new Person[]{
new Person{Name="John", Age=26, Birthday=new DateTime(1986,1,1)},
new Person{Name="Tom", Age=10, Birthday=new DateTime(2002, 1, 9)}
};
return Json(persons, JsonRequestBehavior.AllowGet);
}
Normally, I got the result like this:
[{“Name”:”John”,”Age”:26,”Birthday”:”/Date(504892800000)/”},{“Name”:”Tom”,”Age”:10,”Birthday”:”/Date(1010505600000)/”}]
That’s okay, however, I want to make an option for the user: not to display birthday. So, the expecting result would be like this:
[{“Name”:”John”,”Age”:26},{“Name”:”Tom”,”Age”:10}]
How can I not to serialize the Birthday property to JSON?
You have two options:
1) Add a [ScriptIgnore] attribute to the Person class:
2) Return an anonymous type that contains only the properties you want:
EDIT: I wasn’t aware that the desired columns had to be dynamically chosen. You can use the following because objects and dictionaries are the same thing in Javascript.
First, create an extension that creates a dictionary of your desired properties:
Next, use this extension method before serializing: